我想编写一个 Shell(AWK,Sed 也可以)程序,将单行文本作为输入。
这将在其中任意传播整数字符串。例如
“12884 和 111933 是两个数字,323232 也是一个数字”
我希望输出是
“12,884 和 1,11,933 是两个数字,而 2,23,232 也是一个数字”
如果这是 PHP,一个简单的 preg_replace_callback 就可以达到目的,但我希望它在 shell 中。:/
任何指针都会有很大帮助。
我想编写一个 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
我还使用 globbing 来测试一系列数字,而不是依赖于是否会产生错误的东西,这取决于它是否是整数。
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' ' '
我知道这可能又长又丑,但现在是我能做的最好的,我希望它会有所帮助。
遵循解释: