26

How to cut the last field in this shell string

LINE="/string/to/cut.txt"

So that the string would look like this

LINE="/string/to/"

Thanks in advance!

4

5 回答 5

69

对于它的价值,cut基于 - 的解决方案:

NEW_LINE="`echo "$LINE" | rev | cut -d/ -f2- | rev`/"
于 2011-04-03T21:48:50.353 回答
23

I think you could use the "dirname" command. It takes in input a file path, removes the filename part and returns the path. For example:

$ dirname "/string/to/cut.txt"
/string/to
于 2010-12-30T13:47:47.833 回答
19

这将适用于现代 Bourne 版本,如 Dash、BusyBox ash 等,以及 Bash、Korn shell 和 Z shell 等后代。

LINE="/string/to/cut.txt"
LINE=${LINE%/*}

或保留最后的斜线:

LINE=${LINE%/*}/
于 2010-12-30T15:30:29.460 回答
1

echo $LINE | grep -o '.*/'也可以。

于 2011-02-12T21:47:28.140 回答
1
echo "/string/to/cut.txt" | awk -F'/' '{for (i=1; i<NF; i++) printf("%s/", $i)}'
于 2010-12-30T13:52:55.437 回答