Monday, November 1, 2021

[SOLVED] Bash: How to get some lines from a file and save output to another file

Issue

I have a log file like this

$ cat build.log
..........
[ 60% 60917/101076] AAPT2 compile ....
[ 60% 60918/101076] AAPT2 compile ....
[ 60% 60919/101076] AAPT2 compile ....
[ 60% 60920/101076] AAPT2 compile ....
ninja: build stopped: subcommand failed.
21:41:22 ninja failed with: exit status 1

#### failed to build some targets (17:26 (mm:ss)) ####

How to generate like a new parsed logs so the output of the new file log is like this:

$ cat parsed.log
[ 60% 60920/101076] AAPT2 compile ....
ninja: build stopped: subcommand failed.
21:41:22 ninja failed with: exit status 1

#### failed to build some targets (17:26 (mm:ss)) ####

Like only get the last progress [ 60% 60920/101076] until the end of the file, using maybe grep, sed, or anything. Thank you


Solution

Here is a perl:

$ perl -0777 -lne 'print $1 if /(^\[[^[]*\z)/m' file

Or a perl pipe:

$ perl -E 'say reverse <>' file | perl -lpE 'if (/^\[/){ say; last}' | perl -E 'say reverse <>'

For an awk you can do:

$ awk 'BEGIN{RS="\\["}END{print "[" $0}' file

Of course, you may know that if the failure is always 3 lines, the simplest is just use tail:

$ tail -n 3 file

All print:

[ 60% 60920/101076] AAPT2 compile ....
ninja: build stopped: subcommand failed.
21:41:22 ninja failed with: exit status 1


Answered By - dawg