Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining columns within a single file using awk

Tags:

awk

I am trying to reformat a large file. The first 6 columns of each line are OK but the rest of the columns in the line need to be combined in increments of 2 with a "/" character in between.

Example file (showing only a few columns but have many more in actual file):

1       1       0       0       1       2       A       T       A       C

Into:

1       1       0       0       1       2       A/T     A/C

So far I have been trying awk and this is where I am at...

awk '{print $1,$2,$3,$4,$5; for(i=7; i < NF; i=i+2) print $i+"/"+$i+1}'  myfile.txt > mynewfile.txt
like image 338
KBoehme Avatar asked Aug 06 '13 23:08

KBoehme


People also ask

How do I concatenate two columns in Unix?

paste is the command that can be used for column-wise concatenation. The paste command can be used with the following syntax: $ paste file1 file2 file3 …

How do I print two columns in awk?

We can also print multiple columns and insert our custom string in between columns. For example, to print the permission and filename of each file in the current directory, use the following set of commands: $ ls -l | awk '{ print $1 " : " $8 }' -rw-r--r-- : delimited_data.

How do I print space in awk?

To place the space between the arguments, just add " " , e.g. awk {'print $5" "$1'} .


1 Answers

awk '{for(i=j=7; i < NF; i+=2) {$j = $i"/"$(i+1); j++} NF=j-1}1' input
like image 110
perreal Avatar answered Sep 30 '22 02:09

perreal