2

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/'
4

2 回答 2

6

我认为最好cut用于此:

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

请注意,这cut -d/ -f1-3意味着:根据 delimiter 剥离字符串/,然后从第 1 部分打印到第 3 部分。

或者也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
于 2013-06-13T13:09:50.637 回答
3

您可以使用 POSIX 定义的参数替换:

$ s="/home/auto/gift/surprise"
$ echo ${s%/*/*}
/home/auto
于 2013-06-13T13:55:14.383 回答