Reputation: 2987
Using sed -n "s/.*\(\/.*\/\).*/\1/p
on /string1/string2
produces string1, as expected.
However, using the same on /string1/string2/string3
produces string2.
How can I print the first occurrence only, that is string1.
This does exactly what I wanted:
sed -n "s/[^/]*\(\/[a-z]*\).*/\1/p"
Upvotes: 0
Views: 1352
Reputation: 58381
This might work for you (GNU sed):
sed -n 's/[^\/]*\(\/[^\/]*\/\).*/\1/p' file
Upvotes: 0
Reputation: 246774
perl's non-greedy regex quantifiers are handy:
perl -pe 's{.*?(/.*?/).*}{$1}' <<END
foobar/string1/string2/string3
END
/string1/
If you want to use bash shell:
str="foobar/string1/string2/string3"
string1=$( IFS=/; set -- $str; echo $2 )
Upvotes: 0
Reputation: 785058
You can use this sed:
sed -n 's|/\([^/]*\)/.*|\1|p'
Avoid escaping /
by using an alternate delimiter.
Upvotes: 3