How to conditionally replace column values ​​with the value of a specific column on the same row with Unix and awk commands

I want to conditionally replace column values ​​with the value of a specific column on the same line in a single file, with Unix and awk commands.

For example, I have myfile.txt (3 rows, 5 columns, with tab delimiters):

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

There is "." in columns 3 through 5. I want to replace those with "." in columns 3 through 5 with the value in column 2 on the same row.

Could you show me any directions?

+3
source share
2 answers

This is similar to what you are asking:

% 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 have asked some questions (and have not accepted any answers!) On awk now. May I humbly offer a textbook ?

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

All Articles