I'm trying to write a bash script that increments the version number which is given in
{major}.{minor}.{revision}
For example.
1.2.13
Is there a good way to easily extract those 3 numbers using something like sed or awk such that I could increment the {revision} number and output the full version number string.
Small variation on fgm's solution using the builtin
read
command to split the string into an array. Note that the scope of theIFS
variable is limited to theread
command (so no need to store & restore the currentIFS
variable).See: How do I split a string on a delimiter in Bash?
I prefer "cut" command for this kind of things
I know this is not the shortest way, but for me it's simplest to understand and to read...
I use the shell's own word splitting; something like
although you need to be careful with version numbers in general due to alphabetic or date suffixes and other annoyingly inconsistent bits. After this, the positional parameters will be set to the components of
$version
:(
$IFS
is a set of single characters, not a string, so this won't work with a multicharacter field separator, although you can useIFS=.-
to split on either.
or-
.)Here is how it works:
The string is split in two parts.
${v%.*}
${v##*.}
The first part is printed as is, followed by a plain dot and the last part incremented using shell arithmetic expansion:
$((x+1))
Awk makes it quite simple:
echo "1.2.14" | awk -F \. {'print $1,$2, $3'}
will print out 1 2 14.flag -F specifies separator.
If you wish to save one of the values:
firstVariable=$(echo "1.2.14" | awk -F \. {'print $1'})
Yet another shell way (showing there's always more than one way to bugger around with this stuff...):
So, we can do: