Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

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

*** Note ***

Comments are welcome. But in order to reject spam posts please consider following rules:
  1. Comments with string http are rejected with message You have no rights to use this tag
  2. All comments are reviewed by hand and thus it usually takes one day until a comment will be published.