Extract version number from file in shell script

2020-02-19 05:46发布

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.

8条回答
唯我独甜
2楼-- · 2020-02-19 06:29

Small variation on fgm's solution using the builtin read command to split the string into an array. Note that the scope of the IFS variable is limited to the read command (so no need to store & restore the current IFS variable).

version='1.2.33'
IFS='.' read -r -a a <<<"$version"
((a[2]++))
printf '%s\n' "${a[@]}" | nl
version="${a[0]}.${a[1]}.${a[2]}"
echo "$version"

See: How do I split a string on a delimiter in Bash?

查看更多
做个烂人
3楼-- · 2020-02-19 06:35

I prefer "cut" command for this kind of things

major=`echo $version | cut -d. -f1`
minor=`echo $version | cut -d. -f2`
revision=`echo $version | cut -d. -f3`
revision=`expr $revision + 1`

echo "$major.$minor.$revision"

I know this is not the shortest way, but for me it's simplest to understand and to read...

查看更多
Explosion°爆炸
4楼-- · 2020-02-19 06:38

I use the shell's own word splitting; something like

oIFS="$IFS"
IFS=.
set -- $version
IFS="$oIFS"

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:

$1 = 1
$2 = 2
$3 = 13

($IFS is a set of single characters, not a string, so this won't work with a multicharacter field separator, although you can use IFS=.- to split on either . or -.)

查看更多
Root(大扎)
5楼-- · 2020-02-19 06:42
$ v=1.2.13
$ echo "${v%.*}.$((${v##*.}+1))"
1.2.14

$ v=11.1.2.3.0
$ echo "${v%.*}.$((${v##*.}+1))"
11.1.2.3.1

Here is how it works:

The string is split in two parts.

  • the first one contains everything but the last dot and next characters: ${v%.*}
  • the second one contains everything but all characters up to the last dot: ${v##*.}

The first part is printed as is, followed by a plain dot and the last part incremented using shell arithmetic expansion: $((x+1))

查看更多
再贱就再见
6楼-- · 2020-02-19 06:44

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'})

查看更多
仙女界的扛把子
7楼-- · 2020-02-19 06:45

Yet another shell way (showing there's always more than one way to bugger around with this stuff...):

$ echo 1.2.3 | ( IFS=".$IFS" ; read a b c && echo $a.$b.$((c + 1)) )
1.2.4

So, we can do:

$ x=1.2.3
$ y=`echo $x | ( IFS=".$IFS" ; read a b c && echo $a.$b.$((c + 1)) )`
$ echo $y
1.2.4
查看更多
登录 后发表回答