bash 如果数字不总是相同,如何在多个文件中增加数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/374438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to increment a number in several files if the number is not always the same?
提问by Barth
I have several files containing this line
我有几个包含这一行的文件
Release: X
I want to increment X in all the files.
我想在所有文件中增加 X。
If X was constant between the files, I could have a bash script looping around the files and doing ($1 containing the former release number and $2 the new one, ie. $1 + 1) :
如果 X 在文件之间保持不变,我可以有一个 bash 脚本在文件周围循环并执行 ($1 包含以前的版本号和 $2 新版本,即 $1 + 1):
sed 's/Release: ''/Release: ''/' <$file >$file.new
Now, how should I do if the release number is different between files ?
现在,如果文件之间的版本号不同,我该怎么办?
Is it doable with sed ?
用 sed 可行吗?
should I use another tool ?
我应该使用其他工具吗?
回答by Adam Liss
Use awk- it's exactly the right tool for this:
使用awk- 这正是用于此目的的正确工具:
awk '/Release: [0-9]+/ { printf "Release: %d\n", +1 }' < $file > $file.new
Translation:
翻译:
- Search for lines that contain "Release: " followed by one or more digits.
- Print "Release: " followed by a number and a newline. The number is the second word in the input line (the digits), plus 1.
- 搜索包含“发布:”后跟一位或多位数字的行。
- 打印“Release:”后跟一个数字和一个换行符。数字是输入行中的第二个单词(数字)加上 1。
回答by The Archetypal Paul
This perl one-liner will do the same as the awk script, but not destroy the rest of the file or the rest of the lines that contain the release.
这个 perl one-liner 将执行与 awk 脚本相同的操作,但不会破坏文件的其余部分或包含发布的其余行。
perl -pe "$_=~s/Release: (\d+)/'Release: '. (+1)/e;" < file > file.new

