0

我有一个 csv 文件,其数据如下

16:47:07,3,r-4-VM,230000000.,0.466028518635,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,0.50822578824,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.488406067907,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.467893525702,131072,0,0,0,0,0

我想缩短第 5 列中的值。

期望的输出

16:47:07,3,r-4-VM,230000000.,0.46,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,0.50,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.48,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.46,131072,0,0,0,0,0

非常感谢您的帮助

4

6 回答 6

4
awk '{$5=sprintf( "%.2g", $5)} 1' OFS=, FS=, input

这将四舍五入并打印.47而不是.46在第一行,但也许这是可取的。

于 2013-05-09T05:07:39.747 回答
1

你想要它在 perl 中,就是这样:

perl -F, -lane '$F[4]=~s/^(\d+\...).*/$1/g;print join ",",@F' your_file

测试如下:

> cat temp
16:47:07,3,r-4-VM,230000000.,0.466028518635,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,10.50822578824,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.488406067907,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.467893525702,131072,0,0,0,0,0
> perl -F, -lane '$F[4]=~s/^(\d+\...).*/$1/g;print join ",",@F' temp
16:47:07,3,r-4-VM,230000000.,0.46,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,10.50,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.48,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.46,131072,0,0,0,0,0
于 2013-05-09T05:22:08.260 回答
1

如果不需要四舍五入,即0.466028518635需要打印为 0.46,请使用:

cat <input> | awk -F, '{$5=sprintf( "%.4s", $5)} 1' OFS=,

(这可以是另一个无用使用 cat 的例子)

于 2013-05-09T05:18:31.083 回答
1

试试这个:

cat filename | sed 's/\(^.*\)\(0\.[0-9][0-9]\)[0-9]*\(,.*\)/\1\2\3/g'

到目前为止,输出是 GNU/Linux 标准输出,所以

cat filename | sed 's/\(^.*\)\(0\.[0-9][0-9]\)[0-9]*\(,.*\)/\1\2\3/g' > out_filename

将所需的结果发送到out_filename

于 2013-05-09T05:09:11.473 回答
0
sed -r 's/^(([^,]+,){4}[^,]{4})[^,]*/\1/' file.csv
于 2013-05-09T05:33:02.453 回答
0

这可能对您有用(GNU sed):

sed -r 's/([^,]{,4})[^,]*/\1/5' file

这将第 5 次出现的非逗号替换为不超过 4 个字符的长度。

于 2013-05-09T06:05:57.583 回答