4

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

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

zedoo
  • 10,003
  • 12
  • 43
  • 54

4 Answers4

5

Assuming your string is in 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.

Dennis Williamson
  • 324,833
  • 88
  • 366
  • 429
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"
sorpigal
  • 24,422
  • 8
  • 57
  • 73
0

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

Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
0

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

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

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

Will
  • 3,190
  • 4
  • 29
  • 38