Removing characters from a Bash variable
Use parameter expansion to remove everything from the first /
:
$ k="111.111.111.111/24"
$ echo "${k%%/*}"
111.111.111.111
See this parameter extension resource for more information:
http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion
$ {parameter% pattern}
The "pattern" is matched against the end of the "parameter". As a result, the extended value of the "parameter" with the least match is removed.
$ {parameter %% pattern}
As above, but the longest match is removed.
So you can remove from the latter /
with one %
:
$ k="111.111.111.111/24/23"
$ echo "${k%/*}"
111.111.111.111/24
source to share
Another way:
k="111.111.111.111/24"
echo "${k/%\/24/}"
It replaces the last one with /24
an empty string.
$ {parameter / pattern / string}
The template is expanded to create a template in the same way as the filename extension. The parameter is expanded and the largest match of the pattern against its value is replaced with a string. If the pattern starts with '/, all pattern matches are replaced with the string. Usually only the first match is replaced. If the pattern starts with '#, it must match the beginning of the extended parameter value. If the pattern starts with '%, it must match at the end of the extended parameter value. If string is null, pattern matches are removed and / pattern can be omitted. If the parameter is '@ or', the replacement operation is applied to each positional parameter in turn, and the expansion is the resulting list. If the parameter is an array variable with "@ or" index, the substitution operation is applied to each member of the array in turn.and the extension is the resulting list.
source to share