awk或sed来更改文件中的列值

我有一个数据如下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 

我想缩短第五栏的价值。

期望的输出

 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 

您的帮助是高度赞赏

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

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

试试这个:

 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

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

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

(这可以用猫的另一个例子无用 )

你想在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 
 sed -r 's/^(([^,]+,){4}[^,]{4})[^,]*/\1/' file.csv 

这可能适用于你(GNU sed):

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

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