user558134
user558134

Reputation: 1129

How to cut the last field from a shell string

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!

Upvotes: 31

Views: 65599

Answers (5)

user554272
user554272

Reputation: 278

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

Upvotes: 23

Lucas Jones
Lucas Jones

Reputation: 20183

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

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

Upvotes: 78

mohit6up
mohit6up

Reputation: 4348

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

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 359985

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%/*}/

Upvotes: 19

ajreal
ajreal

Reputation: 47321

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

Upvotes: 1

Related Questions