例如,我需要删除第25列,并在没有嵌入分隔符的简单csv文件中将其替换为第22列的副本。我能想到的最好的是尴尬的样子:
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}'
我希望有类似的东西
cut -d, -f1-24,23,26-59
工作但切割似乎不想两次打印相同的列...
使用linux shell环境中可用的任何东西,有更优雅的方法吗?
答案 0 :(得分:4)
告诉awk用字段22替换字段25.
awk 'BEGIN{FS=","; OFS=","} {$25=$22; print}' < test.csv
答案 1 :(得分:0)
它并不优雅,但paste
是coreutils
的一部分,应该可用,但它需要一些临时文件:
$ 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
或者,您可以跳过最后一个临时文件并使用标准输入:
$ 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
答案 2 :(得分:0)
这可能对您有用:
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
或者如果您愿意:
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