使用 perl 或 awk 搜索文件中的数字,并从命令行将其按常量增加
我有一个文件,其中有一堆 3 位数的数字,我需要将它们增加一定的量(实际上,我需要将所有大于某个值的数字增加恒定的量)。如何从命令行尽可能简单地完成此操作?
编辑:为了澄清,文件中的文本不仅仅是数字,而且将它们提取为 awk 中的字段并不容易。
I have a file that has a bunch of 3-digit numbers that I need to increase by a certain amount (actually, I need to increase all numbers that are greater than a certain value by a constant amount). How can I do this as simply as possible from the command line?
EDIT: To clarify, there is more text in the file than just numbers, and it's not easy to extract them as fields in awk.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
下面是一个示例,它将取文件中大于 400 的每个数字(好吧,正整数)并加上 13。
\d+
是匹配文本中任何整数的正则表达式$&
是一个特殊的 Perl 变量,包含与正则表达式匹配的文本。在这种情况下,它将是一个数字。/e
修饰符告诉 Perl 评估替换表达式。在这种情况下,它评估$& > 400? $&+13 : $&
获取不同的数字。'/g' 修饰符替换每行上正则表达式(整数)的所有实例。
Here is an example that will take every number (well, positive integer) in a file that is greater than 400 and add 13 to it.
\d+
is the regular expression that will match any integer in your text$&
is a special Perl variable that contains the text that was matched by a regular expression. In this case, it would be a number.The
/e
modifier tells Perl to evaluate the replacement expression. In this case, it evaluates$& > 400 ? $&+13 : $&
to get a different number.The '/g' modifier replaces all instances of the regular expression (the integer) on each line.
怎么样:
变成:
变成:
How about:
Turns:
into:
这可能不是最紧凑的,但这是我首先想到的:
This is probably not optimally compact, but it's the first thing I thought of:
假设文件有 3 位数字,以换行符分隔:
Assuming file has 3 digit numbers separated by newlines: