将第二列从正变为负,反之亦然

时间:2014-02-21 09:20:36

标签: bash unix sed awk

如何将第二列从正面更改为负面,反之亦然

aa.txt文件

31OCT2013:00:00:00,220.10,"O","090500 13549951"
31OCT2013:00:00:00,-0.32,"I","090500 13549964"

答案应该是

aa.txt文件

31OCT2013:00:00:00,-220.10,"O","090500 13549951"
31OCT2013:00:00:00,+0.32,"I","090500 13549964"

如果我使用awk

'BEGIN{FS=OFS=","} {$2=-$2}1' aa.txt

结果是

1OCT2013:00:00:00,-220.1,"O","090500 13549951"
31OCT2013:00:00:00,+0.32,"I","090500 13549964"

在第一个结果中,符号正在更改但缺少0,而不是-220.10,它显示为-220.1

3 个答案:

答案 0 :(得分:1)

sed 's/^\([^,]*,\)-/\1/
t
s/^[^,]*,/&-/' YourFile

基于-存在

答案 1 :(得分:0)

考虑到您想要基于逗号更改第二列,这可能是一种方式:

$ awk 'BEGIN{FS=OFS=","} {$2=-$2}1' aa.txt
31OCT2013:00:00:00,-220.1,"O","090500 13549951"
31OCT2013:00:00:00,0.32,"I","090500 13549964"

31OCT2013:00:00:00,-220.1,"O","090500 13549951"
                   ^
31OCT2013:00:00:00,0.32,"I","090500 13549964"
                   ^

更新

根据算术行为,在之前的版本中,我们丢失了尾随零。为了正确处理它,我们可以做到:

awk 'BEGIN{FS=OFS=","} {if ($2>0) $2="-"$2; else sub("-", "", $2)}1' file

如果值为正,则在字符串前添加短划线。否则,它只是删除破折号。

给出样本文件

$ cat a
31OCT2013:00:00:00,220.10,"O","090500 13549951"
31OCT2013:00:00:00,-0.32,"I","090500 13549964"
31OCT2013:00:00:00,0.300,"I","090500 13549964"
31OCT2013:00:00:00,-0.300,"I","090500 13549964"
31OCT2013:00:00:00,0,"I","090500 13549964"

返回

$ awk 'BEGIN{FS=OFS=","} {if ($2>0) $2="-"$2; else sub("-", "", $2)}1' a
31OCT2013:00:00:00,-220.10,"O","090500 13549951"
31OCT2013:00:00:00,0.32,"I","090500 13549964"
31OCT2013:00:00:00,-0.300,"I","090500 13549964"
31OCT2013:00:00:00,0.300,"I","090500 13549964"
31OCT2013:00:00:00,0,"I","090500 13549964

答案 2 :(得分:0)

使用sprintf格式化输出。

awk 'BEGIN{FS=OFS=","} {$2=sprintf("%+.2f",-$2)}1' aa.txt