frankc
frankc

Reputation: 11473

Copy one column over another in a delimited file

For instance, I needed to remove column 25 and replace it with a copy of column 22 in a simple csv file with no embedded delimiters. The best I could come up with was the awkward looking:

awk -F, '{ for(x=1;x<25;x++){printf("%s,", $x)};printf("%s,",$22);for(x=26;x<59;x++){printf
("%s,", $x)};print $59}'
I would expect something like
cut -d, -f1-24,23,26-59 
to work but cut doesn't seem to want to print the same column two times...

Is there a more elegant way to do it using anything typicaly available in a linux shell environment?

Upvotes: 1

Views: 4461

Answers (3)

potong
potong

Reputation: 58430

This might work for you:

echo '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26' |
sed 's/^\(\([^,]*,\)\{21\}\([^,]*,\)\([^,]*,\)\{2\}\)[^,]*,/\1\3/'
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,22,26

or if you prefer:

echo '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26' | 
sed -r 's/^(([^,]*,){21}([^,]*,)([^,]*,){2})[^,]*,/\1\3/'
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,22,26

Upvotes: 0

Kaleb Pederson
Kaleb Pederson

Reputation: 46479

It's not elegant, but paste is part of coreutils and should be available, but it will take some temporary files:

$ cat test.csv
one,two,three,four,five,six,seven
1,2,3,4,5,6,7
$ cut -d, -f1-5 test.csv > start.txt
$ cut -d, -f3 test.csv> replace.txt
$ cut -d, -f7 test.csv > end.txt
$ paste -d, start.txt replace.txt end.txt
one,two,three,four,five,three,seven
1,2,3,4,5,3,7

Or, you can skip the last temporary file and use standard input:

$ cut -d, -f7 test.csv | paste -d, start.txt replace.txt -
one,two,three,four,five,three,seven
1,2,3,4,5,3,7

Upvotes: 0

jamessan
jamessan

Reputation: 42667

Just tell awk to replace field 25 with field 22.

awk 'BEGIN{FS=","; OFS=","} {$25=$22; print}' < test.csv

Upvotes: 4

Related Questions