如何使用 awk/sed 更改小数点分隔符?
如何使用 sed
或 awk
将数字格式(不同的小数点分隔符)从 XXXXXX.XXX
更改为 XXXXXX,XXX
?
How to change number format (different decimal separator) from XXXXXX.XXX
to XXXXXX,XXX
using sed
or awk
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
你想要有多严格?您可以更改所有
.
字符,正如其他人所建议的那样,但是如果您有的不仅仅是数字,这将导致很多误报。更严格一点的是要求点两边都有数字:这确实允许在一些奇怪的情况下进行更改,即
255.255.255.0
和a1.1a
,但可以干净地处理“正常”数字。How rigorous do you want to be? You could change all
.
characters, as others have suggested, but that will allow a lot of false positives if you have more than just numbers. A bit stricter would be to require that there are digits on both sides of the point:That does allow changes in a couple of odd cases, namely
255.255.255.0
anda1.1a
, but handles "normal" numbers cleanly.如果您想出于装饰目的替换小数分隔符
在大多数情况下
tr
可能是替换字符的最简单方法:当然,如果您处理输入混合数字和字符串,您将需要更强大的方法,例如 Michael J. Barber 提出的方法,甚至更多。
如果您想替换小数分隔符以进行计算默认
情况下,
gawk
(GNUawk
,即大多数 GNU/Linux 发行版的awk
)使用点作为小数分隔符:但是您可以使用
--use-lc-numeric
选项强制它使用当前区域设置的小数分隔符:如果输入格式与当前语言环境不同,您当然可以暂时重新定义 LC_NUMERIC:(
制作人员和其他链接)
If you want to replace the decimal separator for cosmetic purposes
In most cases
tr
is probably the easiest way to substitute characters :Of course if you deal with input mixing numbers and strings, you will need a more robust approach, like the one proposed by Michael J. Barber or even more.
If you want to replace the decimal separator for computation purposes
By default
gawk
(GNUawk
, i.e. theawk
of most GNU/Linux distributions) uses the dot as decimal separator :However you can force it to use the decimal separator of the current locale using the
--use-lc-numeric
option :If the input format is different from the current locale, you can of course redefine LC_NUMERIC temporarily :
(Credits and other links)
当OP谈论数字时,这不是更准确吗……以确保它是点之前的前导数字。该文件可以包含 OP 不想替换的其他点。
Wouldn't this be more accurate as the OP whas talking about numbers.. to make sure it is a leading number before the dot. The document could hold other dots that the OP don't want to substitute.
要仅替换这一行中的小数逗号:
我使用了反向引用(和 MacOSX,所以我需要 -E 选项):
导致
sed 命令说:“查找 '双引号 digital_1,digit_2 形式的每个字符串,后跟一个或零%,双引号'并将其替换为first_match.second_match。”
To substitute only the decimal commas in this line:
I used back-references (and MacOSX, so I need the -E option):
resulting in
The sed command says: "Find every string of the form 'double quotes digit_1,digit_2, followed by one or zero %, double quotes' and replace it by first_match.second_match."
我认为
应该满足你想要的...除非你想要更特别的东西...
I think
should serve what u want... unless u want something more special...
如果你有 bash/ksh 等
if you have bash/ksh etc
你可以这样做:
You could do this:
由于问题也被标记为
awk
:Since the question is also tagged
awk
: