使用 sed 查找并划分文件中的所有数字 [英] Find and divide all numbers in a file using sed
问题描述
我正在尝试在 json 文件中查找所有数字,并在 mac 上使用 sed 将它们替换为原始数字的一半值.比如这里我搜索2010,替换成1005:
I am trying to find all numbers in a json file and replace them with a half value of the original number using sed on mac. For example, here I search for 2010 and replace it with 1005:
file="data.json"
sed -i '' -E 's,([^0-9]|^)2010([^0-9]|$),\1 1005\2,g' "$file"
我想找到所有数字实例,并用它们自己的一半值替换它们.它需要处理小数,例如:2009 将变为 1004.5,10.5 将变为 5.25.
I would like to find all number instances, and replace them with half values of themselves. It would need to work on decimals, eg: 2009 would become 1004.5, 10.5 would become 5.25.
我知道这可能需要每个单独的数字字符,所以可能需要找到两边都带有非数字字符的数字.
I'm aware this could take each individual number character, so perhaps it would need to find numbers with non-numerical characters either side of it.
edit:我希望它能够灵活处理所有形式的文本文件,而不仅仅是 JSON 文件.(.txt、.html、.rtf 等...)
edit: I would like it to be flexible and work on all forms of text files, not just JSON files. (.txt, .html, .rtf etc...)
推荐答案
您可以将 Perl 与带有 e
修饰符的正则表达式一起使用:
You may use Perl with a regex with e
modifier:
perl -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{$1/2}ge' file
要修改文件内联,添加-i
选项:
To modify the file inline, add -i
option:
perl -i -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{$1/2}ge' file
perl -pi.bak -e 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{$1/2}ge' file # To save a backup of the original file
查看在线演示:
s="abc_2010_and+2009+or-10.5"
perl -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{$1/2}ge' <<< "$s"
# => abc_1005_and+1004.5+or-5.25
(? 正则表达式匹配
(?<!\d)
- 不允许紧靠左边的数字(\d+(?:\.\d+)?)
- 第 1 组 ($1
):1+ 位数字后跟可选的序列.
和 1+ 位数字(?!\d)
- 不允许紧靠右侧的数字.
(?<!\d)
- no digit immediately to the left is allowed(\d+(?:\.\d+)?)
- Group 1 ($1
): 1+ digits followed with an optional sequence of.
and 1+ digits(?!\d)
- no digit immediately to the right is allowed.
RHS - $1/2
- 是一个将 Group 1 值除以 2
的表达式.它是通过在正则表达式的末尾添加 e
修饰符来实现的.
The RHS - $1/2
- is an expression that divides the Group 1 value with 2
. It is achieved through adding e
modifier at the end of the regex.
这篇关于使用 sed 查找并划分文件中的所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!