Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find a substring inside a bash variable [duplicate]

Tags:

bash

we were trying to find the username of a mercurial url:

default = ssh://[email protected]//srv/hg/repo

Suppose that there's always a username, I came up with:

tmp=${a#*//}
user=${tmp%%@*}

Is there a way to do this in one line?

like image 667
zedoo Avatar asked Feb 25 '23 18:02

zedoo


2 Answers

Assuming your string is in a variable like this:

url='default = ssh://[email protected]//srv/hg/repo'

You can do:

[[ $url =~ //([^@]*)@ ]]

Then your username is here:

echo ${BASH_REMATCH[1]}

This works in Bash versions 3.2 and higher.

like image 153
Dennis Williamson Avatar answered Feb 28 '23 06:02

Dennis Williamson


You pretty much need more that one statement or to call out to external tools. I think sed is best for this.

sed -r -e 's|.*://(.*)@.*|\1|' <<< "$default"
like image 36
sorpigal Avatar answered Feb 28 '23 07:02

sorpigal