tourist
tourist

Reputation: 544

grep command to know whther the two strings are in specific order

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

Answers (3)

CWLiu
CWLiu

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

RomanPerekhrest
RomanPerekhrest

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

anubhava
anubhava

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

Related Questions