views:

936

answers:

2

Hi,

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 ?

+7  A: 

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.
Adam Liss
Thanks a lot, it is exactly what I was looking for. I will now look for a tutorial about awk and learn more about it.
Barth
You will also want to make sure to define one file as the master "source" for the version. So all other files should get their version from that single source.
Aaron Digulla
Hi Aaron, this is already done :)
Barth
Adam, I just realised that some files contain more than just this Release line and the rest of the content is wiped out by awk. How can I change only this line, without removing the others ?
Barth
Use {print $0} to print those lines except the 'Release line'. Should be simple. Please refer to the manuals for the exact syntax.
Vijay Dev
or switch to Perl - see my other answer :)
Paul
For records, I ended up with the following, but I am sure there are nicer ways of doing it :awk '/Release: /{printf "Release: %d\n", $2+1};!/Release: /{print}' < $file > $file.new
Barth
Your final result will still discard stuff on a line after the release number (e.g. "Release 2: These are not the droids you're looking for" will turn into "Release 3"). That may not be an issue for your situation, of course.
Paul
+3  A: 

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 -pe "$_=~s/Release: (\d+)/'Release: '. ($1+1)/e;" < file > file.new
Paul