如何将第二列从正数更改为负数,反之亦然
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
。
sed 's/^([^,]*,)-/1/
t
s/^[^,]*,/&-/' YourFile
基于-
存在
考虑到您想要更改基于逗号的第二列,这可以是一种方法:
$ 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
使用sprintf格式化输出。
awk 'BEGIN{FS=OFS=","} {$2=sprintf("%+.2f",-$2)}1' aa.txt