Guilty Spark
Guilty Spark

Reputation: 89

sed capture to get string between slashes

I have a filepath like this: /bing/foo/bar/bin and I want to extract only the string between bing/ and the next slash.

So /bing/foo/bar/bin should just produce "foo".

I tried the following:

echo "/bing/foo/bar/bin" | sed -r 's/.*bing\/(.*)\/.*/\1/'

but this produces "foo/bar" instead of "foo".

Upvotes: 1

Views: 35

Answers (1)

Victor Lee
Victor Lee

Reputation: 2678

Try this command

echo "/bing/foo/bar/bin" | sed -r 's|.*bing/([^/]*)/.*|\1|'

use | as delimiters instead of / is proper in your case, reference from "Delimiters in sed substitution",

sed can use any character as a delimiter, it will automatically use the character following the s as a delimiter.

or

echo "/bing/foo/bar/bin" | grep -oP "/bing/\K(\w+)"

Upvotes: 2

Related Questions