在逗号之间每隔一个数字后插入字符串中的小数点

时间:2017-04-05 14:14:32

标签: unix awk sed

我需要在逗号之间的每个字符串的每第二个数字后插入一个小数点。

some.file:

JAN,334,333,332,331,330,330,329,328,328,327,327,327

尝试过的代码:

sed -i 's/\B[0-9]\{1\}\>/.&/' some.file

当前输出:

JAN,33.4,333,332,331,330,330,329,328,328,327,327,327

预期输出:

JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7

我尝试的代码似乎只是抓取(看到)第二个逗号前面的数字字符串,而不是逗号中的每个数字字符串。

5 个答案:

答案 0 :(得分:2)

使用:

$ echo "JAN,334,333,332,331,330,330,329,328,328,327,327,327" |sed -e "s/\([0-9]\{2\}\)/\1./g"
JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7

对于现场替换:

sed -i -e "s/\([0-9]\{2\}\)/\1./g" some.file

此处不需要,但更安全的版本可能是:

sed -i -e 's/,\([0-9]\{2\}\)\([0-9]\)/,\1.\2/g' some.file

答案 1 :(得分:2)

您可以使用Awk,如下所示

awk 'BEGIN{FS=OFS=","}{for(i=2;i<=NF;i++) if (length($i) >2) { $i=substr($i,0,2)"."substr($i,3,length($i)); } }1' file

生成输出

JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7

我们的想法是从2nd记录开始循环元素到结束行(最多$NF)并对超过2位的数字应用逻辑

substr()是一个POSIX兼容函数,用于从当前处理的记录中获取子字符串。

  

substr(string,start [,length])

从字符编号开始开始,返回字符串长度 - 字符长子字符串。字符串的第一个字符是第一个字符。

答案 2 :(得分:2)

另一个awk,将所有数字除以10并使用一个小数点打印

awk -v RS=, '{if($1==$1+0) printf "%.1f,", $1/10; else printf "%s,",$1}' file | 
sed '$s/,$/\n/'

JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7

答案 3 :(得分:1)

在awk中使用正则表达式替换:

$ awk 'gsub(/[0-9],|[0-9]$/,".&")||1' file
JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7

说明:

  • gsub(/[0-9],|[0-9]$/,".&")将所有数字+逗号替换为句号+该号码+逗号代替记录末尾的最后一个号码
  • ||
  • 1无论如何都要打印

答案 4 :(得分:1)

sed的另一种方法:

sed -e "s/\b[0-9][0-9]/&./g"