Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two columns of a text file

Tags:

text

awk

gawk

I have a tsv file like

1   2   3   4   5   ...
a   b   c   d   e   ...
x   y   z   j   k   ...

How can I merge two contiguous columns, say the 2nd and the 3rd, to get

1   2-3   4   5   ...
a   b-c   d   e   ...
x   y-z   j   k   ...

I need the code to work with text files with different numbers of columns, so I can't use something like awk 'BEGIN{FS="\t"} {print $1"\t"$2"-"$3"\t"$4"\t"$5}' file

awk is the first tool I thought about for the task and one I'm trying to learn, so I'm very interested in answers using it, but any solution with any other tool would be greatly appreciated.

like image 654
Arch Stanton Avatar asked Jan 03 '23 22:01

Arch Stanton


2 Answers

With simple sed command for tsv file:

sed 's/\t/-/2' file

The output:

1   2-3 4   5   ...
a   b-c d   e   ...
x   y-z j   k   ...
like image 190
RomanPerekhrest Avatar answered Jan 13 '23 11:01

RomanPerekhrest


Following awk may help you in same, in case you are not worried about little space which will be created when 3rd field will be nullified.

awk '{$2=$2"-"$3;$3=""} 1'  Input_file
like image 29
RavinderSingh13 Avatar answered Jan 13 '23 10:01

RavinderSingh13