使用 bash-script 修改 CSV 中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11522786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:47:23  来源:igfitidea点击:

modify value's in CSV with bash-script

bashcsvshbc

提问by Mirco Schmidt

I've the following CSV file's:

我有以下 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

What I want to do is modify the value in the 2nd column...

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

What I already can do is extract the value and modify it this way:

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

#!/bin/bash
cut -d ";" -f2  > .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

But I need to have column1 in that file too...

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

I hope one of you can give me a hint, I'm just stuck!

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

采纳答案by Debaditya

From your code, this is what I understood

从你的代码,这就是我的理解

Input

输入

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 code

awk 代码

awk -F ";" '{print $1 ";" $2/5}' input

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

Output

输出

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

回答by Steve

One way, using awk:

一种方法,使用awk

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

Results:

结果:

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

HTH

HTH

回答by chepner

Here's an almost-pure bashsolution, without temp files:

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

#!/bin/bash

while IFS=$';' read col1 col2; do
    echo "$col1; $(echo "scale=2;$col2/5" | bc -l)"
done

回答by Birei

Try with awk:

尝试awk

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

    {
         = sprintf( "%.2f", /5 )
        print 
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
} ' infile

Output:

输出:

##代码##