Extract substring before dot
Asked Answered
M

3

19

I try to substract the first string before a dot (.) in bash.

For instance:

1.2.3 -> 1
11.4.1 -> 11

I used the following command based on the docs:

s=4.5.0
echo "${s%.*}"

But it ouptuts 4.5 instead of 4. I don't get it.

Why is that?

Monomania answered 22/11, 2016 at 9:40 Comment(1)
echo "${s%%.*}"?Insanity
G
30

You need to use %% to remove the longest match from the end:

$ echo "${s%%.*}"
4

From the docs:

${parameter%%word}
Remove Largest Suffix Pattern. The word shall be expanded to produce a pattern. The parameter expansion shall then result in parameter, with the largest portion of the suffix matched by the pattern deleted.

Goahead answered 22/11, 2016 at 9:41 Comment(0)
J
4

You can also use the bash Regular Expressions feature built-in in the recent versions of the shell (since bash 3.0), using the tilde(=~) operator.

$ string="s=4.5.0"
$ [[ $string =~ =([[:alnum:]]+).(.*) ]] && printf "%s\n" "${BASH_REMATCH[1]}"
4
$ string="s=32.5.0"
$ [[ $string =~ =([[:alnum:]]+).(.*) ]] && printf "%s\n" "${BASH_REMATCH[1]}"
32
Jericajericho answered 22/11, 2016 at 9:52 Comment(0)
L
0

Alternatively, you could use cut

s=4.5.0
echo $s | cut -d '.' -f 1
Lithoid answered 28/11, 2022 at 0:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.