duplicate a column with awk

I have some tab delimited data and I need to duplicate the second column. It seems like I should just be able to do something simple in awk like,

awk '{ print $1, $2, $2, $3 }'

(the second field is the one that needs to be duplicated)

but I'm not sure how to print from $3 to the end of the line ($3-$NF???) and I'm not sure how the tabs will be preserved.

LMHmedchem

The output separator is controlled by the special variable OFS.

Perhaps you can cheat a little, putting two values in one column:

awk 'BEGIN { FS="\t"; OFS="\t" } { $2=$2 "\t" $2 } 1'
1 Like

Thanks, that worked fine.

Another quick question, is there an easy way to append something like "MC_" to every field on the first line?

fieldName1    fieldName2    fieldName3

MC_fieldName1    MC_fieldName2    MC_fieldName3

LMHmedchem

1 Like
awk 'BEGIN { FS="\t"; OFS="\t"; }; NR==1 { for(N=1; N<=NF; N++) $N="MC_" $N; }; 1'

It will run the loop only for the first line. But the "; 1" should cause it to print all lines.

1 Like