Chip
Chip

Reputation: 471

How to merge column output to the end of a row in the previous column?

I have a .csv file containing three columns and I need to merge the value of column 2 with the end of the row of column 1.

The .csv file contains thousands of rows and this needs to be done for each row.

Iv'e tried using awk but I'm finding it difficult to get the code correct

cat file.csv | awk '{print $1, $2}' 

awk '{if ($2!= " ") {print $1+$2 }}'

These of course don't work

Sample input:

The command used to produce the actual output is simply: cat test.csv

[2,4,5,6,2,34,61,32,34,54,34,       22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,       34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,       21]     0.347643

Desired Output:

             col1                       col2
[2,4,5,6,2,34,61,32,34,54,34,22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,21]     0.347643

Upvotes: 1

Views: 122

Answers (3)

vintnes
vintnes

Reputation: 2030

Replace "comma followed by one or more spaces" with "comma":

sed 's/, \{1,\}/,/' file.csv
sed 's/, */,/g' file.csv

Print columns $1 and $2 as $1 (optionally separate with a tab):

awk '{print $1 $2, $3}' OFS='\t' file.csv

Upvotes: 2

Paul Hodges
Paul Hodges

Reputation: 15293

I only see spaces after a comma when you don't want them.

$: sed -E 's/,\s+/,/' file.csv
[2,4,5,6,2,34,61,32,34,54,34,22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,21]     0.347643

Add -i (after the -E) to make it an in-place edit.

$: sed -Ei 's/,\s+/,/' file.csv
$: cat file.csv
[2,4,5,6,2,34,61,32,34,54,34,22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,21]     0.347643

Upvotes: 0

xiawi
xiawi

Reputation: 1822

You can try:

awk '{printf("%s%s\t%s\n",$1,$2,$3)}' file.cvs

Upvotes: 0

Related Questions