Reputation: 544
I was trying to write a shell script to check if two strings are present in a file, also, I'm checking if they are in specific order.
Let's say the file.txt
has the following text:
bcd
def
abc
I'm using the command : grep -q abc file.txt && grep -l bcd file.txt
This is giving the output file.txt
when the two strings are present in any order. I'd like to get the output only if abc
comes before bcd
. Please help me with this
Upvotes: 2
Views: 471
Reputation: 4043
awk -v RS='' '/abc.*bcd/{print FILENAME}' file.txt
You may re-assign the RS (record separator) from default '\n'
to ''
, and start to process the whole file as it is in one record. Then it's no problem to use /abc.*bcd/
to distinguish if abc
is ahead bcd
.
Noted that it would not be recognized successfully if an empty line is in the case, since an empty line between abc
and bcd
would split them to different records. That would cause the criterion misjudge.
Upvotes: 1
Reputation: 92854
With grep PCRE option:
grep -Pzl 'abc[\s\S]*bcd' file.txt
-z
- treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.If PCRE (-P
option) is not supported on your side:
grep -zl 'abc.*bcd' file.txt
Upvotes: 3
Reputation: 785286
You can use awk
instead of grep
to match abc
only after bcd
:
awk '/abc/{p=NR} p && /bcd/{print FILENAME; exit}' file
Upvotes: 2