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

家住魔仙堡 提交于 2020-01-14 03:00:11

问题


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.


回答1:


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.



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/17228045/grep-for-a-string-in-a-line-if-the-previous-line-doesnt-contain-a-specific-stri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!