Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print previous line if condition is met

Tags:

linux

grep

awk

I would like to grep a word and then find the second column in the line and check if it is bigger than a value. Is yes, I want to print the previous line.

Ex:

Input file

AAAAAAAAAAAAA
BB  2
CCCCCCCCCCCCC
BB 0.1

Output

AAAAAAAAAAAAA

Now, I want to search for BB and if the second column (2 or 0.1) in that line is bigger than 1, I want to print the previous line.

Can somebody help me with grep and awk? Thanks. Any other suggestions are also welcome. Thanks.

like image 443
Ram Avatar asked Jan 02 '15 10:01

Ram


People also ask

How do I print previous lines in awk?

txt awk "BEGIN { R=0; N=0; } /Header pattern/ { N=1; } { R=R+N; N=0; print R; }" ) .

How do I go to a previous line in Linux?

The easiest way to get at the previous line is to make sure that the current line is unfinished (e.g. type \ at the end), accept it (press Enter ), then cancel it (press Ctrl + C ). Then you can recall the whole stored command as a single history line as a single multi-line buffer by pressing Up . Save this answer.


1 Answers

This can be a way:

$ awk '$1=="BB" && $2>1 {print f} {f=$1}' file
AAAAAAAAAAAAA

Explanation

  • $1=="BB" && $2>1 {print f} if the 1st field is exactly BB and 2nd field is bigger than 1, then print f, a stored value.
  • {f=$1} store the current line in f, so that it is accessible when reading the next line.
like image 61
fedorqui 'SO stop harming' Avatar answered Oct 03 '22 03:10

fedorqui 'SO stop harming'