Skip to content
Advertisement

Print previous line if condition is met

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.

Advertisement

Answer

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.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement