Bash – How to increment a number in several files if the number is not always the same

bashreplacescriptingsearchsed

I have several files containing this line

Release: X

I want to increment X in all the files.

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) :

sed 's/Release: '$1'/Release: '$2'/' <$file >$file.new

Now, how should I do if the release number is different between files ?

Is it doable with sed ?

should I use another tool ?

Best Solution

Use awk - it's exactly the right tool for this:

awk '/Release: [0-9]+/ { printf "Release: %d\n", $2+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.