Find a substring inside a bash variable

we tried to find the username of the mercury URL:

default = ssh://someone@acme.com//srv/hg/repo

Suppose there is always a username, I came up with:

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

Is there a way to do this on a single line?

+3
source share
4 answers

Assuming your string has a variable like this:

url='default = ssh://someone@acme.com//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.

+4
source

To a large extent, you need more than one application or access external tools. I think sed is best suited for this.

sed -r -e 's|.*://(.*)@.*|\1|' <<< "$default"
+3
source

bash. , sed.

0

mercurial, url,

echo 'ssh://someone@acme.com/srv/hg/repo' |grep -E --only-matching '\w+@' |cut --delimiter=\@ -f 1

, , .

0

Source: https://habr.com/ru/post/1776284/


All Articles