简体   繁体   中英

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.

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/ /line1[^\\n]*\\n.*line2/ || /line2[^\\n]*\\n.*line1/ will search 2 keywords on 2 different lines irrespective of their order

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.

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

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";
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM