Search code examples
awkgawkcsh

Awk If-Elseif-If Block


NR>NRMIN{
    if($3 == "Leu") {
        if($4 == "CD1" || $4 == "HD11" || $4 == "HD12" || $4 == "HD13") {
            next;
        }
    }
    elseif($3 == "Val") {
        if($4 == "CD1" || $4 == "HD11" || $4 == "HD12" || $4 == "HD13") {
            next;
        }
    }
    else {
        print;
    }   
}

I intend to selectively print lines of a space-delimited file. Please let me know why the above code is giving an error when gawk -f FILE_Modifier.awk NRMIN = 90 FILE > NEWFILE

Error Message

gawk: FILE_Modifier.awk:7:     elseif($3 == "Val") {
gawk: FILE_Modifier.awk:7:                         ^ syntax error
gawk: FILE_Modifier.awk:12:     else {
gawk: FILE_Modifier.awk:12:     ^ syntax error

Solution

  • There is no elseif. Anyway, you can rewrite the script as just:

    awk -v nrmin=90 '(NR > nrmin) && !(($3 ~ /^(Leu|Val)$/) && ($4 ~ /^(CD1|HD11|HD12|HD13)$/))' file
    

    Don't use all upper case variable names to avoid clashes with builtin names. Do set variables up front using -v unless you have a specific reason not to.