给定一个目录树,我将如何从字符串中删除分隔符的最后一个字段并返回没有该分隔符的字符串,假设我不知道该字符串的结束位置?
例如,给定
/1/2/3/4/5
我知道我可以用
返回5cut -f 5 -d '/'
如果我知道最后一个字段是第5个字段,或者a = / 1/2/3/4/5
echo ${a##*/}
选择最后一个字段。但是,如何返回原始字符串减去最后一个字段呢?即
/1/2/3/4
答案 0 :(得分:1)
您可以使用%
或%%
运算符代替##
。来自Bash手册页:
${parameter%word} ${parameter%%word} The word is expanded to produce a pattern just as in pathname expan- sion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parame- ter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
简而言之,${a%/*}
可以解决问题。
答案 1 :(得分:0)
您可以剪切一系列字段
cut -f 1-4 -d '/'