我想编写一个 Shell(AWK、Sed 也可以)程序来将单行文本作为输入。

其中将任意分布整数字符串。例如

“12884和111933是两个数字,323232也是一个数字”

我想要的输出是

“12,884 和 1,11,933 是两个数字,2,23,232 也是一个数字”

如果这是 PHP,一个简单的 preg_replace_callback 就可以达到目的,但我希望它在 shell 中。:/

任何指示都会有很大帮助。

有帮助吗?

解决方案

这是没有必要分割使用tr线。你可以使用bash的分词功能:

line="12884 and 111933 are two numbers and 323232 is also a number"
for word in $line
do
    if [[ $word = *[^0-9]* ]]
    then
        printf "%s " $word
    else
        printf "%'d " $word
    fi
done

我也用通配符来测试一个数字序列而不是依赖于一些创建错误或不取决于它是否是一个整数。

其他提示

for line in $(echo "12884 and 111933 are two numbers and 323232 is also a number" 
    | tr ' ' '\n');
    do 
        if [ $line -eq $line 2> /dev/null ]; 
            then printf "%'d\n" $line;
        else 
            echo $line; 
        fi; 
    done | tr '\n' ' '

我知道这可能又长又难看,但到目前为止这是我能做的最好的事情,我希望它会有所帮助。

如下解释:

  • 首先,我将行分成更多行,这样我就可以循环并识别哪些字符串是数字,哪些不是数字
  • 然后我测试当前字符串是否是数字
  • 如果它是一个数字,我使用 printf 解析
  • 如果不是,我只是回应它,保持原样
  • 完成循环并将所有内容放回一行
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top