A lot of time you have to split a string into pieces. There exist various ways to get it done. For example you can use sed or grep with a regular experssion. But there are much more efiicient ways available by using plain bash:

Question: How to extract the first and second path from the given string s="someString:/path1/path2/path3/path3/test.bin"

Solution: /path1/path2

Use cut:

echo $(cut -f 2-3 -d / <<< "$s")

Use sed:

echo $(sed -r 's/[^:]+:((\/[^/]+){2})(.*)/\1/' <<< "$s")

Use plain bash and read:

IFS=/ read x a b y <<< "$s"; echo "/$a/$b"

Use plain bash and set:

IFS=/ eval set -- \$s; echo "/$2/$3"
Add comment


Spam comments are purged and not published. Review is done manually and therefore it usually takes between some hours and one day until a comment will be published.