SS Hegde
SS Hegde

Reputation: 739

grep for a string in a line if the previous line doesn't contain a specific string

I have the following lines in a file:

abcdef ghi jkl
uvw xyz

I want to grep for the string "xyz" if the previous line is not contains the string "jkl".

I know how to grep for a string if the line doesn't contains a specific string using -v option. But i don't know how to do this with different lines.

Upvotes: 1

Views: 1480

Answers (3)

Zombo
Zombo

Reputation: 1

sed '/jkl/{N;d}; /xyz/!d'
  • If find jkl, remove that line and next
  • print only remaining lines with xyz

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363818

grep is really a line-oriented tool. It might be possible to achieve what you want with it, but it's easier to use Awk:

awk '
  /xyz/ && !skip { print }
                 { skip = /jkl/ }
' file

Read as: for every line, do

  • if the current line matches xyz and we haven't just seen jkl, print it;
  • set the variable skip to indicate whether we've just seen jkl.

Upvotes: 3

ruakh
ruakh

Reputation: 183602

I think you're better off using an actual programming language, even a simple one like Bash or AWK or sed. For example, using Bash:

(
  previous_line_matched=
  while IFS= read -r line ; do
    if [[ ! "$previous_line_matched" && "$line" == *xyz* ]] ; then
      echo "$line"
    fi
    if [[ "$line" == *jkl* ]] ; then
      previous_line_matched=1
    else
      previous_line_matched=
    fi
  done < input_file
)

Or, more tersely, using Perl:

perl -ne 'print if m/xyz/ && ! $skip; $skip = m/jkl/' < input_file

Upvotes: 0

Related Questions