Bash – How to Split a String by the Third Dot Delimiter

bashshellsplitstring

I did a few research, I can split the string by '.' but the only thing I want to replace is the third '.', and the version number is actually variable so how can I do the replace/split?

version: 1.8.0.110

but What I want is the output like this:

version: 1.8.0-110

Best Answer

Used sed for example:

$ echo 'version: 1.8.0.110' | sed 's/\./-/3'
version: 1.8.0-110

Explanation:

sed s/search/replace/x searches for a string and replaces the second. x determines which occurence to replace - here the 3rd. Often g is used for x to mean all occurances.

Here we wish to replace the dot . but this is a special character in the regular expression sed expects in the search term. Therefore we backslashify the . to \. to specify a literal ..

Since we use special characters in the argument to sed (here, the backslash \) we need to put the whole argument in single quotes ''. Many people always use quotes here so as not to run into problems when using characters that might be special to the shell (like space ).

Related Question