1

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.

2 Answers 2

3

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 ;).

Sign up to request clarification or add additional context in comments.

1 Comment

spot on, thank you. And yes, uid and pwd will not contain those delimiters
0

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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.