Krish Krish - 11 months ago 69
Linux Question

In shell, split a portion of a string with dot as delimiter

I am new to shell scripting, can you please help with below requirement, thanks.

#separate the string after last "-", with "." as delimiter
#that is, separate "" and print/save as below.

Answer Source

First, note that you don't use $ when assigning to a parameter in the shell. Your first line should be just this:


Once you have that, then you can do something like this:

IFS=. read major minor micro build <<EOF

where the ##*- strips off everything from the beginning of the string through the last '-', leaving just "", and the IFS (Internal Field Separator) variable tells the shell where to break the string into fields.

In bash, specifically, you can shorten the here-document to a here-string:

    IFS=. read major minor micro build <<<"${AU_NAME##*-}"

More generally, if you're using a shell that has arrays, you can split into an arbitrarily-sized array instead of distinct variables. This works in bash, zsh, and modern ksh:

IFS=. components=(${AU_NAME##*-})

In older versions of ksh you can do this:

IFS=. set -A components ${AU_NAME##*-}

Which gets you this equivalence (except in zsh, which numbers the elements 1-4 instead of 0-3):