4

我有以下 CSV 文件:

2012-07-12 15:30:09; 353.2
2012-07-12 15:45:08; 347.4
2012-07-12 16:00:08; 197.6
2012-07-12 16:15:08; 308.2
2012-07-12 16:30:09; 352.6

我想要做的是修改第二列中的值......

我已经可以做的是提取值并以这种方式修改它:

#!/bin/bash
cut -d ";" -f2 $1 > .tmp.csv
for num in $(cat .tmp.csv)
    do
        (echo "scale=2;$num/5" | bc -l >> .tmp2.csv)
done
rm .tmp.csv
rm .tmp2.csv

但我也需要在该文件中有 column1 ......

我希望你们中的一个能给我一个提示,我只是卡住了!

4

4 回答 4

3

从您的代码中,这就是我所理解的

输入

2012-07-12 15:30:09; 353.2 
2012-07-12 15:45:08; 347.4 
2012-07-12 16:00:08; 197.6 
2012-07-12 16:15:08; 308.2 
2012-07-12 16:30:09; 352.6 

awk 代码

awk -F ";" '{打印 $1 ";" $2/5}' 输入

输出

2012-07-12 15:30:09;70.64
2012-07-12 15:45:08;69.48
2012-07-12 16:00:08;39.52
2012-07-12 16:15:08;61.64
2012-07-12 16:30:09;70.52
于 2012-07-17T13:09:43.230 回答
3

一种方法,使用awk

awk '{ $NF = $NF/5 }1' file.txt

结果:

2012-07-12 15:30:09; 70.64
2012-07-12 15:45:08; 69.48
2012-07-12 16:00:08; 39.52
2012-07-12 16:15:08; 61.64
2012-07-12 16:30:09; 70.52

高温高压

于 2012-07-17T13:10:23.570 回答
3

这是一个几乎纯正的bash解决方案,没有临时文件:

#!/bin/bash

while IFS=$';' read col1 col2; do
    echo "$col1; $(echo "scale=2;$col2/5" | bc -l)"
done
于 2012-07-17T13:30:30.790 回答
2

尝试awk

awk '
    BEGIN {
        ## Split fields with ";".
        FS = OFS = "; "
    }

    {
        $2 = sprintf( "%.2f", $2/5 )
        print $0
    }
' infile

输出:

2012-07-12 15:30:09; 70.64
2012-07-12 15:45:08; 69.48
2012-07-12 16:00:08; 39.52
2012-07-12 16:15:08; 61.64
2012-07-12 16:30:09; 70.52
于 2012-07-17T12:59:43.117 回答