awk Command – Remove Columns with ‘-‘ in First Line

awktext processing

I have the table

M       -       A       A       -
-       A       G       -       -
M       -       -       -       G

and I want to perform: if any column of the first line contains "-", skip printing the column

The expected output is

M       A       A 
-       G       - 
M       -       - 

I have tried something like this but didn't work

awk 'NR==1 && $i!="-" {print $i}'

Does anyone know how to correct the command?

Best Answer

$ cat tst.awk
NR == 1 {
    for (i=1; i<=NF; i++) {
        if ($i != "-") {
            f[++numOutFlds] = i
        }
    }
}
{
    for (i=1; i<=numOutFlds; i++) {
        printf "%s%s", $(f[i]), (i<numOutFlds ? OFS : ORS)
    }
}

$ awk -f tst.awk file
M A A
- G -
M - -
Related Question