bash 替换 CSV 文件中的列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20425763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace in a CSV file value of a column
提问by Ioannis
I have a a CSV file with this structure:
我有一个具有这种结构的 CSV 文件:
31126000283424431;32285076389;t;text text;1;3;;1;1;0.9;0.81;0;0;1;1;1;2013-11-21;;NL
31126000279521531;32308233749;c;text text;1;2;;1;9;2.79;7.78;0;0;4;16;9;2013-11-21;;NL
31126000279406931;32291254349;c;text text;1;5;;1;3;0.98;0.96;0;0;3;9;0;2013-11-21;;NL
31126000272138431;32284912829;c;text text;1;3;;1;1;0;0;0;0;3;9;0;2013-11-21;;NL
31126000271468431;32304086789;t;text text;1;5;;1;1;0.2;0.04;0;0;2;4;1;2013-11-21;;NL
31126000269838731;29269530509;c;text text;1;1;;1;1;0.45;0.2;0;0;3;9;0;2013-11-21;;NL
and I need to replace the number after the sixth semicolon to 0.
我需要将第六个分号后的数字替换为 0。
So the output file would look like:
所以输出文件看起来像:
31126000283424431;32285076389;t;text text;1;0;;1;1;0.9;0.81;0;0;1;1;1;2013-11-21;;NL
31126000279521531;32308233749;c;text text;1;0;;1;9;2.79;7.78;0;0;4;16;9;2013-11-21;;NL
31126000279406931;32291254349;c;text text;1;0;;1;3;0.98;0.96;0;0;3;9;0;2013-11-21;;NL
31126000272138431;32284912829;c;text text;1;0;;1;1;0;0;0;0;3;9;0;2013-11-21;;NL
31126000271468431;32304086789;t;text text;1;0;;1;1;0.2;0.04;0;0;2;4;1;2013-11-21;;NL
31126000269838731;29269530509;c;text text;1;0;;1;1;0.45;0.2;0;0;3;9;0;2013-11-21;;NL
I have been trying awk, sed, and cut, but I can't get it to work.
我一直在尝试 awk、sed 和 cut,但我无法让它工作。
thank you
谢谢你
回答by Kent
your example shows the 6th col, but after the 5thsemi.
您的示例显示了第 6 列,但在第5半场之后。
awk -F';' -v OFS=';' '=0;7' file
try the line above
尝试上面的行
回答by NeronLeVelu
sed "s/;[^;]\{1,\}/;0/5" YourFile.csv
assume there is always something in colum
假设列中总有一些东西
sed "s/;[^;]*/;0/5" YourFile.csv
change in every case even if there is no number is 6th column
即使没有数字,在每种情况下也会发生变化是第 6 列
回答by Hynek -Pichi- Vychodil
perl -MText::CSV_XS -e'$csv=Text::CSV_XS->new({sep_char=>";", eol=>"\n"}); while($row=$csv->getline(ARGV)) {$row->[5]=0;$csv->print(STDOUT, $row)}'
Use as filter or put input file as parameter. You should use proper CSV parser for any serious work.
用作过滤器或将输入文件作为参数。对于任何严肃的工作,您都应该使用适当的 CSV 解析器。
回答by Samuel Hawksby-Robinson
If you've got php on your machine you could use this very handy CSV Paser class. It will convert your CSV in to a 2D array, from which you can cycle through using a foreach loop and change the data.
如果你的机器上有 php,你可以使用这个非常方便的CSV Paser 类。它会将您的 CSV 转换为二维数组,您可以从中循环使用 foreach 循环并更改数据。
$csvFile
foreach($csvFile as $value){
foreach($value as $k => $v){
if($k == 5){ $v = 0}
}
}
This would automate it for a CSV file of any size of the same format.
这将自动处理任何大小的相同格式的 CSV 文件。