问题
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 seenjkl
, print it; - set the variable
skip
to indicate whether we've just seenjkl
.
回答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