开发者

Copy one column over another in a delimited file

开发者 https://www.devze.com 2022-12-27 07:42 出处:网络
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 b开发者_如何学Cest I could come up with was the awkward looking:

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 b开发者_如何学Cest 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?


Just tell awk to replace field 25 with field 22.

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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消