am28
am28

Reputation: 381

find string on multiple lines of file using awk

I am trying to check if a certain file has two strings. My test file is:
This is line1. This is line2.

In real-time scenario for my application the strings line1 and line2 can be on the same or different lines or have one or more occurrences. The objective is to find if these string exist in the file.

Now, if I run the following command I expect OK to be printed but it doesn't.
cat test_file.sh | awk '$0 ~ /line1/ && /line2/ {print "OK"};'

Can someone please tell what is it that I need to change here.

Upvotes: 1

Views: 2793

Answers (4)

karakfa
karakfa

Reputation: 67497

awk to the rescue!

awk '/pattern1/{s=1} /pattern2/{t=1} s&&t{print "OK"; exit}' file

checks two patterns regardless of the order.

If you want them to be strictly on different lines

awk '/pattern1/{s=1;next}
     /pattern2/{t=1;next}
           s&&t{print "OK"; exit}
            END{if(s&&t) print "OK"}' file

Upvotes: 0

anubhava
anubhava

Reputation: 785156

Your awk command is trying to find line1 and line2 on same line. Correct way to search 2 strings on different lines is:

sed '/^[[:blank:]]*$/d' |
awk -v RS= '/line1[^\n]*\n.*line2/ || /line2[^\n]*\n.*line1/{print "Ok"}'
  • sed will remove all blank lines from input
  • -v RS= will set input record separator as NULL thus ignoring new line as record separator.
  • /line1[^\n]*\n.*line2/ || /line2[^\n]*\n.*line1/ will search 2 keywords on 2 different lines irrespective of their order

Upvotes: 1

Lars Fischer
Lars Fischer

Reputation: 10149

Here we store the line number in which the patterns occur and decide in the end if the input is ok or not.

BEGIN {p1=0; p2=0;}

/This is line1./ { p1 = FNR}
/This is line2./ { p2 = FNR}

END { if( p1== p2 ) {
    print "not ok";
  }
  else {
    print "ok";
  }
}

Upvotes: 0

Skyler
Skyler

Reputation: 186

You can also accomplish this using grep and wc. For example:

cat ./file | grep "line1\|line2" | wc -l

would return the number of lines these two strings ("line1" and "line2") are on. If it returned 1, they are on the same line. If it returned 2, they are on separate lines.

Upvotes: 1

Related Questions