2016-02-23 5 views
3

Учитывая дерево каталогов, как бы я хотел сократить последнее поле разделителя из строки и вернуть строку без этого разделителя, предполагая, что я не знаю, где эта строка заканчивается?Вырезание секции из строки и возвращение противоположного

Например, с учетом

/1/2/3/4/5 

Я знаю, что может вернуть 5 с

cut -f 5 -d '/' 

если я знаю, последнее поле является 5-один, или если а =/1/2/3/4/5

echo ${a##*/} 

, чтобы выбрать последнее поле. Но как я могу вернуться к исходной строке минус последнее поле? т.е.

/1/2/3/4 
+2

'Эхо $ {а%/*}'. –

ответ

1

Вы можете использовать оператор % или %% вместо ##. От Баш человек-странице:

${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%/*} будет делать трюк.

+0

Ой, ты прав. – paddy

0

Вы можете дать сократить набор полей

cut -f 1-4 -d '/'