Search code examples
shellunixawksedgawk

Compare and print unmatched string in unix


I have file like

123|3a|3b
747|3a|3b|3c|3d
636|3c|3b

Output :

123 -3c 3d
636 -3a 3d 

It should compare 3a,3b,3c,3d and show the missing one .

I tried using

awk '/3a/3b/3c/3d' file.txt

but not able to figure out how to compare single string.


Solution

  • $ cat list
    3a,3b,3c,3d
    $
    $ cat file
    123|3a|3b
    747|3a|3b|3c|3d
    636|3c|3b
    $
    $ cat tst.awk
    NR==FNR {
        for (i=1; i<=NF; i++) {
            reqd[++numReqd] = $i
        }
        next
    }
    {
        c=0
        for (i=1; i<= numReqd; i++) {
            if ( $0 !~ "[|]" reqd[i] "([|]|$)" ) {
                printf "%s%s%s%s", (++c>1?"":$1), OFS, (c>1?"":"-"), reqd[i]
            }
        }
        if (c) {
            print ""
        }
    }
    $
    $ awk -f tst.awk FS=',' list FS='|' file
    123 -3c 3d
    636 -3a 3d