Search code examples
awkmatchnawk

nawk/awk: How to present an error message while there is no string match?


I'll start by saying that this forum is an excellent source of knowledge. I need your help in presenting No Match error message.

printf "some\nwhere\nonly\nwe\nknow\n" > test.txt 

I'm looking for 'only' string and if there is a match, it will be presented

nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=0 s="only" test.txt | awk '{if ($0 ~ /only/) print; else print "No Match"}'

Output: only

If I'm looking for 'only' string and checking if there is also apple on this line, I'll get No match message

nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=0 s="only" test.txt | awk '{if ($0 ~ /apple/) print; else print "No Match"}'

Output: No Match

BUT if I'm looking for 'apple' string (there is no such) and check if it's there, I don't get 'No Match' message.

nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=0 s="apple" test.txt | awk '{if ($0 ~ /apple/) print; else print "No Match"}'

The output is blank. How can I change this behaviour, I want to get 'No Match' message.


Solution

  • in awk.

    If the searchphrase isn't found at all.

    awk '/searchphrase/{c++} END{if(c == 0) print "No Match"}' file
    

    If you want to print no match for every line without a match.

    awk '!/searchphrase/{print "No Match"}' file
    

    If you want to still print searchphrase when found

    awk '/searchphrase/{c++; print} END{if(c == 0) print "No Match"}' file