Results 1 to 3 of 3
I prefer to delete trailing slahes from pathes. Until now I used sed:
Code:
$ myPath=/home/ladygaga///
$ echo "$myPath" | sed 's/\/*$//'
/home/ladygaga
I played around to accomplish the same ...
- 12-08-2010 #1Just Joined!
- Join Date
- Dec 2010
- Posts
- 16
[SOLVED] delete trailing slashes using bash on-board means
I prefer to delete trailing slahes from pathes. Until now I used sed:
I played around to accomplish the same with on-board means of bash without using sed, but for example this line only deletes one trailing slash:Code:$ myPath=/home/ladygaga/// $ echo "$myPath" | sed 's/\/*$//' /home/ladygaga
Is there a way to delete trailing slahes with just on-board means of bash?Code:$ myPath=/home/ladygaga/// $ echo ${myPath%/*} /home/ladygaga//
- 12-10-2010 #2
There are various problems here. The most serious is that this pattern:
isn't a regex mechanism, it's a globbing mechanism. So * isn't the Kleene Star (i.e. "match zero or more instances of the previous element") - it's a multi-character wildcard. (i.e. "match any zero or more consecutive characters") Also, the "%" removal mechanism removes the shortest match from the end of the string. To get the longest one, use "%%"...Code:${var%PATTERN}
So the pattern you're using will actually remove everything from the last slash in the string onward...
Globbing syntax isn't (by default) versatile enough to give you real Kleene Star functionality. However, Bash does provide an extension to globbing syntax to correct this. It's off by default, probably for compatibility reasons. Anyway...Code:a='a/b/c' echo ${a%/*} # Prints "a/b" echo ${a%%/*} # Prints "a"
If you'd rather use regular expressions and avoid dealing with "shopt" - use substring matching to extract the portion of the string before any consecutive slashes at the end of the string:Code:shopt -s extglob #Turns globbing extensions on echo ${myPath%%*(/)} #The *() syntax is the Kleene Star in Bash's extended globbing syntax... Here it's matching zero or more slashes at the end of the string. shopt -u extglob #Turns globbing extensions back off.
Or, alternately:Code:pattern='^(.*[^/])/*$' # Parenthesized subexpression may contain anything, but ends with a character that's not slash - remainder of string is zero or more slashes. [[ $myPath =~ $pattern ]] #Apply regex echo ${BASH_REMATCH[1]} #Print the match from the first parenthesized subexpression.
Code:# pattern='^.*[^/]' #Regular expressions are "greedy", they'll match the longest substring they can from the position where they find a match. This matches from the start of the source string, any string ending with a non-slash. [[ $myPath =~ $pattern ]] #Apply regex echo ${BASH_REMATCH[0]} #Print the portion of the source string which matched the regex.
- 12-10-2010 #3Just Joined!
- Join Date
- Dec 2010
- Posts
- 16
Brilliant! Thanks a bunch!



