我有一个巨大的 csv 文件,数字末尾有 -(减号)符号。现在我需要将这些 - 减号移动到数字的开头,即我需要删除最后一个字符(如果它有“-”号)并将“-”号放在前面。
0.00,70440.19-,18.31-,0.00,451.59-,13788.77-,44.19-,6289.29-
1.03-,39.24-,0.11-,16.96-,0.00,72377.70-,0.00,146673.67-,59.11-,0.00
我尝试了下面的方法,但如果有十进制值“.”字符,然后在前面添加减号:
perl -pe 's#(\d{1,})(-)#$2$1#'g file
输出如下:
0.00,70440.-19,18.-31,0.00,451.-59,13788.-77,44.-19,6289.-29
1.-03,39.-24,0.-11,16.-96,0.00,72377.-70,0.00,146673.-67,59.-11,0.00
请建议任何 awk / sed / perl 一个衬垫来完成这项工作?
问候,维诺。
答案1
下面的解决方案有效:任何其他 awk 或 sed 解决方案都会很高兴知道......
perl -pe 's#(\d{1,}[.]\d{1,})(-)#$2$1#'g file
答案2
与 perl 命令相同,
$ sed 's/\([0-9]\+\.[0-9]\+\)-/-\1/g' file
0.00,-70440.19,-18.31,0.00,-451.59,-13788.77,-44.19,-6289.29
-1.03,-39.24,-0.11,-16.96,0.00,-72377.70,0.00,-146673.67,-59.11,0.00
另一个 Perl 单行代码,
$ perl -pe 's/([^,\n]*?)-/-\1/g' file
0.00,-70440.19,-18.31,0.00,-451.59,-13788.77,-44.19,-6289.29
-1.03,-39.24,-0.11,-16.96,0.00,-72377.70,0.00,-146673.67,-59.11,0.00
答案3
另一个perl
perl -F, -lane 'print join ",", map {(/-$/ && chop) . $_} @F' file
答案4
以下是一些:
更短的 perl
perl -pe 's/([\d.]+)-/-$1/g' file
(GNU) sed
sed -r 's/([0-9.]+)-/-\1/g' file
任何 sed
sed 's/\([0-9.]*\)-/-1\1/g' file
呆呆的。请注意,各种 awk 变体不太擅长涉及捕获模式的任务。 GNU awk (gawk) 和其他人可以做到这一点,但我会使用上面的解决方案之一。
gawk -F, '{ for(i=1; i<NF; i++){ if(sub(/-/,"",$i)){printf "-%s,",$i} else{printf "%s,",$i} } if(sub(/-/,"",$NF)){print "-"$NF} else{print $NF} }' file
我确信一定有更好的 awk 方法来做到这一点,但上面的方法尽管丑陋且麻烦,但仍然可以工作。
不必要的复杂
perl -pe 's/\n/\n\n/; s/,/\n/g; ' file | awk -F"-" '/-/{printf "-";}{print $1}' | perl -000ne 's/\n./,/g;s/\n\n/\n/g; print'