jianfeng.mao
jianfeng.mao

Reputation: 945

how to conditionally replace values in columns with value of specific column in the same line by Unix and awk commands

I want to conditionally replace values in columns with value of specific column in the same line in one file, by Unix and awk commands.

For example, I have myfile.txt (3 lines, 5 columns, tab-delimited):

1 A . C .
2 C T . T
3 T C C .

There are "." in columns 3 to 5. I want to replace those "." in columns 3 - 5 with the value in column 2 on the same line.

Could you please show me any directions on that?

Upvotes: 3

Views: 6859

Answers (2)

jlliagre
jlliagre

Reputation: 30853

awk '{FS="\t"; for(i=3;i<=5;i++) if($i==".") $i=$2; print}' myfile.txt

Upvotes: 4

johnsyweb
johnsyweb

Reputation: 141928

This seems to do what you're asking for:

% awk 'BEGIN {
     IFS = OFS = "\t"
  }
  {
     for (column = 3; column <= NF; ++column) {
        if ($column == ".") {
            $column = $2
        }
     }    
     print 
  }         
' test.tsv
1       A       A       C       A
2       C       T       C       T
3       T       C       C       T

You've asked a few questions (and accepted no answers!) on awk now. May I humbly suggest a tutorial?

Upvotes: 5

Related Questions