Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut the last field from a shell string

Tags:

string

shell

cut

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!

like image 781
user558134 Avatar asked Dec 30 '10 13:12

user558134


People also ask

How do I remove the last character of a string in bash?

To remove the last n characters of a string, we can use the parameter expansion syntax ${str::-n} in the Bash shell. -n is the number of characters we need to remove from the end of a string.

How do I cut a string in bash?

There is a built-in function named trim() for trimming in many standard programming languages. Bash has no built-in function to trim string data. But many options are available in bash to remove unwanted characters from string data, such as parameter expansion, sed, awk, xargs, etc.

How do I split a string on a delimiter in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.


5 Answers

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

NEW_LINE="`echo "$LINE" | rev | cut -d/ -f2- | rev`/"
like image 101
Lucas Jones Avatar answered Oct 05 '22 10:10

Lucas Jones


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
like image 34
user554272 Avatar answered Oct 05 '22 11:10

user554272


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%/*}/
like image 20
Dennis Williamson Avatar answered Oct 05 '22 11:10

Dennis Williamson


echo "/string/to/cut.txt" | awk -F'/' '{for (i=1; i<NF; i++) printf("%s/", $i)}'
like image 33
ajreal Avatar answered Oct 05 '22 12:10

ajreal


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

like image 35
mohit6up Avatar answered Oct 05 '22 11:10

mohit6up