我想用一位小数减去数字......
我用:
awk -F "," '{$4=$3-$2 ;print $1"," $2"," $3"," $4"}' file.csv
现在我只获得单位,我需要一个小数,我该怎么办?
输入数据
London,18.2,19,1
Liverpool,6.3,9,3
Manchester,15.1,17,2
答案 0 :(得分:0)
您可以在printf
awk
awk -F "," '{printf ("%s,%2.1f,%2.1f,%2.1f\n", $1,$2, $3,$3-$2)}' file.cvs
它允许使用类似于C
或FORTRAN
的字符串格式。
您可以在 printf语句中看到man awk
。男人的摘录
%f, %F A floating point number of the form [-]ddd.dddddd.
If the system library supports it, %F is available as well. This is like %f,
but uses capital letters for special “not a number” and “infinity” values.
%g, %G Use %e or %f conversion, whichever is shorter, with nonsignificant
zeros suppressed. The %G format uses %E instead of %e.
%s A character string.
...
输出
London,18.2,19.0,0.8
Liverpool,6.3,9.0,2.7
Manchester,15.1,17.0,1.9
如果您使用逗号,
而不是点.
来将小数部分与整数1分开,则这取决于local settings。您可以在选项中为所有系统搜索更改它们,也可以仅为当前shell或子shell更改它们。您可以尝试使用
( LC_ALL=C ; awk -F "," '{printf ("%s,%2.1f,%2.1f,%2.1f\n", $1,$2, $3,$3-$2)}' file.cvs )
( ... )
使其在子shell中运行,因此您不会更改当前LC_ALL
中shell
的值。
答案 1 :(得分:0)
以打印方式计算答案:
echo "10.5 1.1" | awk '{print "Solution:" $1-$2}'
在你的情况下:
awk -F "," '{print $1"," $2"," $3"," $3-$2}' file.csv
刚检查了你的代码,并提到了ooga:
awk -F "," '{$4=$3-$2; print $1"," $2"," $3"," $4}' file.csv
没有“最后也应该工作。