gpt4 book ai didi

bash - 将所有数字缩写转换为文本文件中的数值

转载 作者:行者123 更新时间:2023-12-04 04:27:12 24 4
gpt4 key购买 nike

我想将文本文件中的所有数字缩写(例如 1K、100K、1M 等)转换为纯数值,例如 1000、100000、1000000 等。
例如,如果我有以下文本文件:

1.3K apples
87.9K oranges
156K mangos
541.7K carrots
1.8M potatoes
我想在 bash 中将其转换为以下内容:
1300 apples
87900 oranges
156000 mangos
541700 carrots
1800000 potatoes
我使用的命令是用完整的数值替换匹配的数字缩写字符串,如下所示:
sed -e 's/1K/1000/g' -e 's/1M/1000000/g' text-file.txt
我的问题是,当发生变化时,我无法找到并替换所有可能的数字缩写。我想这样做直到至少有一位十进制缩写。

最佳答案

使用 numfmt 来自 GNU coreutils,不要重新发明轮子。

$ numfmt --from=si <file
1300 apples
87900 oranges
156000 mangos
541700 carrots
1800000 potatoes
如果缩写数字可能显示为任何字段,则您可以使用:
numfmt --from=si --field=- --invalid=ignore <file

关于bash - 将所有数字缩写转换为文本文件中的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65536137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com