Reputation: 36656
I haver few files (same file name) with this text
version: 24
runtime: python27
How can I increment the version number in all of them from the cmd?
I can do easy sed
command, but I'm looking for smart increment and not just replacing text
sed -i '' -e 's/24/25/g' PATH
Upvotes: 1
Views: 92
Reputation: 2471
With gnu sed
sed '/version: /{h;s/.*\( [0-9]*\)/echo $((\1+1))/e;x;s/ .*//;G;s/\n/ /}' infile
Upvotes: 1
Reputation: 37227
sed surely does the job but it's not a good idea to stick to it. A little bash trick would be better.
VER=$(grep 'version' filename | grep -oE '[0-9]+')
sed -i "/version/s/$VER/$((VER+1))/" filename
It's really a trick because sed can't do arithmetic calculations, so I overloaded that job to bash and use sed to do text replacement only.
For convenience use, you may want to wrap them up:
incr_ver() {
VER=$(grep 'version' "$1" | grep -oE '[0-9]+')
(( $? )) || sed -i "/version/s/$VER/$((VER+1))/" "$1"
}
And apply them to each file:
for file in *
do
incr_ver "$file"
done
Upvotes: 1
Reputation: 88583
With awk:
awk '/^version:/ {$2++}; {print}' file
Or shorter:
awk '/^version:/ {$2++}1' file
Ouput:
version: 25 runtime: python27
Upvotes: 5
Reputation: 23667
sed
is not suitable for arithmetic operations, you can use perl
here
$ perl -pe 's/\d+/$&+1/e if /version/' ip.txt
version: 25
runtime: python27
s/\d+/$&+1/e
the e
modifier allows Perl code in replacement section. $&
contains the matched string (similar to &
in sed), $&+1
is the result you need
if /version/
this substitution will happen only when input line contains version
For in-place editing, use perl -i -pe 's/\d+/$&+1/e if /version/' /path/to/files
See
https://perldoc.perl.org/perlrun.html#Command-Switches for explanations on -i
and -pe
options
Upvotes: 2