开发者

How to cut the last field from a shell string

开发者 https://www.devze.com 2023-02-02 00:16 出处:网络
How to cut the last field in this shell string LINE=\"/string/to/cut.txt\" So that the string would look like t开发者_Go百科his

How to cut the last field in this shell string

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

So that the string would look like t开发者_Go百科his

LINE="/string/to/"

Thanks in advance!


For what it's worth, a cut-based solution:

NEW_LINE="`echo "$LINE" | rev | cut -d/ -f2- | rev`/"


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


This will work in modern Bourne versions such as Dash, BusyBox ash, etc., as well as descendents such as Bash, Korn shell and Z shell.

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

or to keep the final slash:

LINE=${LINE%/*}/


echo "/string/to/cut.txt" | awk -F'/' '{for (i=1; i<NF; i++) printf("%s/", $i)}'


echo $LINE | grep -o '.*/' works too.

0

精彩评论

暂无评论...
验证码 换一张
取 消