Search code examples
stringunixawkpattern-matchingnawk

How do I check for a NAWK substring being several possible values?


I am very, very much a beginner with NAWK (or AWK) but I know that you can check for a substring value using:

nawk '{if (substr($0,42,4)=="ABCD") {print {$0}}}' ${file}

(This is being run through UNIX, hence the '$0'.)

What if the string could be either ABCD or MNOP? Is there an easy way to code this as a one-liner? I've tried looking but so far only found myself lost...


Solution

  • Assuming your values are not regex metacharacters, you could say:

    nawk 'substr($0,42,4)~/ABCD|MNOP/' ${file}
    

    If the values contain metacharacters ([, \, ^, $, ., |, ?, *, +, (, )), then you'd need to escape those with a \.