1

I'm trying to retrieve the first and last row of awk command, but I'm not able to. Where I'm making mistakes.

egrep 'updateAll|update-mgr|Startup REX|configd.*UnitProperty updated' $LOG | \ awk 'NR == 1{print $1" "$2" "$3} NR == $#{print $1" "$2" "$3}' awk: cmd. line:2: NR == 1{print $1" "$2" "$3} NR == $#{print $1" "$2" "$3} awk: cmd. line:2: ^ syntax error 

I expect first row and last row form the output of grep command.

1
  • 1
    $# has no meaning in awk ... and if it understood the bashism it still wouldn't do what you want. Commented Jun 21, 2019 at 17:07

3 Answers 3

2

Btw - most of the time when you use grep & awk in one command you're doing it wrong ;)

awk ' { if ($0~/updateAll|update-mgr|Startup REX|configd.*UnitProperty updated/) { c++ l=$0 if(c==1){print} } } END{print l} ' $LOG 
Sign up to request clarification or add additional context in comments.

Comments

1

Use NR == 1 to get the first line, and END to get the last line.

Having this input:

$ echo -e '1 a v\n2 b w\n3 c x\n4 d y\n5 e z' 1 a v 2 b w 3 c x 4 d y 5 e z 

we can parse it using this awk command:

$ echo -e '1 a v\n2 b w\n3 c x\n4 d y\n5 e z' | awk 'NR == 1 { print $2; } END { print $2; }' a e 

Comments

0

@tink solution is correct. I just wish to add that: .

Using variable l is bad practice, since it can be mistaken to 1 or I depending on the current font.

The default match pattern can be extracted as filter pattern for record processing.

So @tink solution becomes:

awk ' /updateAll|update-mgr|Startup REX|configd.*UnitProperty updated/ { c++; lastLine = $0; if(c == 1){print} } END{print lastLine} ' $LOG 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.