开发者

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

开发者 https://www.devze.com 2023-03-10 16:21 出处:网络
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.

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 colu开发者_开发问答mns 3 - 5 with the value in column 2 on the same line.

Could you please show me any directions on that?


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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号