Grep one line before the match plus the match

awkgrepsedtext processing

zzzzzzzzz
aaaaaaaaa
bbbbbbbbb &
ccccccccc &
ddddddddd
hhhhhhhhh
eeeeeeeee
fffffffff &
ggggggggg &

in the above line, what i want is to grep/sed/awk (any method is fine) line that have & sign plus one line on top of them. so for example the desired output will look like :

aaaaaaaaa
bbbbbbbbb &
ccccccccc &
eeeeeeeee
fffffffff &
ggggggggg &

following is what i have tried with no luck.

egrep "&" | -b 1 file.txt

Best Answer

You can do:

grep -B 1 '&$' your_file

This will look for lines ending in &, remove $ to match lines with & anywhere in them.

The -B switch tells grep to output "context" lines that come before the lines that match. In this case, since you want one line of context, you need -B 1.

This switch is available in GNU grep but is not in the POSIX standard, though.

Here's a simple sed solution that should help in case you don't have GNU grep:

sed -n '/&/!N;/&/p' your_file

How it works

  • The -n switch suppresses the default "print" action of sed
  • /&/!N means: if the current line doesn't contain &, append the next line to the pattern space.
  • /&/p means: match & and print the pattern space.
Related Question