4

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?

1
  • Does using a semi-colon between the two operations (instead of a newline) count? Commented Nov 22, 2010 at 22:40

4 Answers 4

5

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.

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

Comments

3

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"

2 Comments

I don't remember seeing that construct before - the <<< - so I just learned something new. Usually I echo the variable into sed; I would imagine this construct is more efficient?
I imagine it is, since an echo and a pipe means a whole 'nother subshell whereas a here string is handled in process.
0

Not within bash itself. You'd have to delegate to an external tool such as sed.

Comments

0

Not familiar with mercurial, but using your url, you can do

echo 'ssh://[email protected]/srv/hg/repo' |grep -E --only-matching '\w+@' |cut --delimiter=\@ -f 1

Probably not the most efficient way with the two pipes, but works.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.