Reputation: 3276
I'm new to shell programming.
I have a String representation of a db connection looking like that:
<user>:<password>@<host>
And I would like to extract each attribute (user, password and host) from the String.
Upvotes: 1
Views: 212
Reputation: 116
Bash string manipulation can be done as follow:
input="<user>:<password>@<host>"
colonPos=$(expr index "${input}" ':')
atPos=$(expr index "${input}" '@')
user=${input:0:$colonPos-1}
pass=${input:$colonPos:$atPos-$colonPos-1}
host=${input:$atPos}
echo -e "input: ${input}\nuser: ${user}\npass: ${pass}\nhost: ${host}"
It also doesn't works with many :
and/or @
, but you can play with:
tmpStr="${input//[^\:]/}"
colonAmount=${#tmpStr}
tmpStr="${input//[^@]/}"
atAmount=${#tmpStr}
echo -e "colon(s) amount: ${colonAmount}\nat(s) amount: ${atAmount}"
Let's play with if then elif else fi
using those *Amount
variables to develop your own parser in bash !
Upvotes: 0
Reputation: 54551
A naive way to do it would be:
$ IFS=:@ read -a args <<< "<user>:<password>@<host>"
$ echo ${args[0]}
<user>
$ echo ${args[1]}
<password>
$ echo ${args[2]}
<host>
Obviously, this won't work if the username or password can contain a ':' or '@' character, or if your host happens to be an IPv6 address ;).
Upvotes: 3