Print previous line along with matched line

Viewed 450

I want to search for pattern and if matched then print the matched line and previous line. I used code

awk '/pattern/ {print a}{a=$0}' file

But it is only printing the previous line of matched line. How can I print print previous line along with matched line.

3 Answers

In your current approach, when the pattern matches you are first printing a and then set it to the value of the current line.

The effect of this is that a always has the value of the previous line. If the match is on the first line, you will print an empty string as a has no value yet.


Besides remembering the current line in a and printing it in the next iteration, you also have to print the current line $0 when the pattern matches.

awk '/pattern/ {
  if (a) print a
  print $0
}
{
  a=$0
}' file

If the value of a can also be an empty string or evaluate numerically to zero as pointed out in the comments by Ed Morton, you can start printing a from the second row on.

awk '
/regexp/ {
  if(FNR>1) { print a }
  print $0
}
{
  a=$0
}' file

You are on right path, You forgot to print the current line simply do.

awk '
/pattern/{
  if(prev)  { print prev ORS $0 }
  if(FNR==1){ print             }
  next
}
{
  prev=$0
}
' Input_file

I have also taken care of 1st first line here, in case pattern comes in very first line then it will simply print that line, since there is no previous line.

Explanation: Adding detailed explanation for above.

awk '                                 ##Starting awk program from here.
/pattern/{                            ##Checking for specific pattern here.
  if(prev)  { print prev ORS $0 }     ##Checking if prev is NOT NULL then print prev newline current line.
  if(FNR==1){ print             }     ##Checking if its first line then simply print the line.
  next                                ##next will skip all further statements from here.
}
{
  prev=$0                             ##Setting prev to current line here.
}
' Input_file                          ##Mentioning Input_file name here.
Related