user2482324
user2482324

Reputation: 23

Select first part of string

How do I pull a substring from a string. For example, from the string:

'/home/auto/gift/surprise'

take only:

'/home/auto/'

Note that '/home/auto/gift/surprise' may vary, i.e., instead of having 4 directory levels, it may go to 6 or 8, yet I'm only interested in the first 2 folders.

Here's what I've tried so far, without success:

$ pwd
'/home/auto/gift/surprise' 
$ pwd | sed 's,^\(.*/\)\?\([^/]*\),\1,'
'/home/auto/gift/'

Upvotes: 2

Views: 135

Answers (2)

Rubens
Rubens

Reputation: 14768

You may use parameter substitution, which is POSIX defined:

$ s="/home/auto/gift/surprise"
$ echo ${s%/*/*}
/home/auto

Upvotes: 3

fedorqui
fedorqui

Reputation: 289745

I think it is better to use cut for this:

$ echo "/home/auto/gift/surpris" | cut -d/ -f1-3
/home/auto
$ echo "/home/auto/gift/surpris/bla/bla" | cut -d/ -f1-3
/home/auto

Note that cut -d/ -f1-3 means: strip the string based on the delimiter /, then print from the 1st to the 3rd parts.

Or also awk:

$ echo "/home/auto/gift/surpris" | awk -F/ 'OFS="/" {print $1,$2,$3}'
/home/auto
$ echo "/home/auto/gift/surpris/bla/bla" | awk -F/ 'OFS="/" {print $1,$2,$3}'
/home/auto

Upvotes: 6

Related Questions