Awk/Sed: Search Pattern from file and Print

Hi,

I want to search for patterns (from a file) in a file and print the line matching the patterns and the line before it.

I have to search for 100s of patterns from a file.

Any help with AWK or Sed.

Thanks!

You can use grep with option -f and -B

grep -B 1 -f pattern_file search_file
1 Like

Make the patterns file into a sed or awk script. In sed, to have the line before is a bit inconvenient, a looping sed:

sed -n '
  :loop
  $q
  N
  /\nPATTERN_1/b p
  /\nPATTERN_2/b p
  . . .
  :x
  s/.*\n//
  b loop
  :p
  p
  b x
 ' data_file
  

grep does it so simply, one wonders why awk and sed? ex might be good for this, too.

1 Like