将给定文本行中的所有数字替换为其货币格式

发布于 2024-08-03 13:37:39 字数 256 浏览 5 评论 0原文

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

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

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

我希望输出为

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

如果这是PHP,一个简单的preg_replace_callback将服务于目的,但我希望这是在外壳中。 :/

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

I want to write a Shell (AWK, Sed also fine) program to take as a input a SINGLE line of text.

Which will have arbitrarily spread integer strings in it. e.g

"12884 and 111933 are two numbers and 323232 is also a number"

I want the output to be

"12,884 and 1,11,933 are two numbers and 2,23,232 is also a number"

If this was PHP a simple preg_replace_callback would have served the purpose but I want this to be in shell. :/

Any pointers would of great help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叫嚣ゝ 2024-08-10 13:37:39

没有必要使用 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 来测试数字序列,而不是依赖于是否会产生错误(取决于它是否是整数)的东西。

It's not necessary to split the line using tr. You can make use of Bash's word splitting feature:

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

I've also used globbing to test for a sequence of digits rather than relying on something that creates an error or not depending on whether it's an integer.

背叛残局 2024-08-10 13:37:39
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 进行解析(
  • 如果它是)我不是简单地回显它,离开它
  • 完成循环并将所有内容放回一行
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' ' '

I understand this may be long and ugly but by now is the best I could do, I hope it will help.

Follows the explanation:

  • fist I split the line on more lines so I can loop and recognize which strings are number and which are not
  • then I test if the current string is a number
  • if it is a number I parse with the usage of printf
  • if it is not I simply echo it, leaving as it was
  • finish the loop and put everything back on one line
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文