Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim trailing and leading slash in bash - joining param substitutions?

Tags:

bash

shell

sh

I'm trying to trim a possible / from the start and end of a string in bash.

I can accomplish this via the following:

string="/this is my string/"
string=${string%/}
string=${string#/}
echo $string # "this is my string"

however, I would like to know if there's a way to join those two lines (2 + 3) to replace both at once. Is there a way to join the substitution, or is that the best I'm going to get?

Thanks in advance.

like image 376
whitfin Avatar asked Jun 13 '14 18:06

whitfin


People also ask

How do you trim leading and trailing spaces in Unix?

`sed` command is another option to remove leading and trailing space or character from the string data. The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command.

How do you remove slash in sed?

Since the text we are dealing with contains / , we're using % as an alternative delimiter in the sed expressions. This first removes the string . git (possibly followed by a / ) from the end of each line of input before applying the same substitution as in the first sed command.


2 Answers

Coming to this very late... You can use bash variable substitution. It can remove a leading OR trailing optional slash, but it can't do both at the same time. If we execute:

VAR1=/one/two/
VAR2=one/two
echo ${VAR1} ${VAR2}
echo ${VAR1#/} ${VAR2#/}
echo ${VAR1%/} ${VAR2%/}

then we get:

/one/two/ one/two            # No change
one/two/ one/two             # No leading slashes
/one/two /one/two            # No trailing slashes

As we can see, slashes inside the variables remain unaltered.

You can combine them using an intermediate variable as:

VAR3=${VAR1#/}               # Remove optional leading slash
VAR3=${VAR3%/}               # Remove optional trailing slash
echo ${VAR3}
like image 85
Stormcloud Avatar answered Nov 15 '22 21:11

Stormcloud


Another pure bash solution (v3.2 or above), using =~ for regex matching and the special $BASH_REMATCH array variable to reference capture group results.

string='/this is my string/'
[[ $string =~ ^/(.*)/$ ]] && string=${BASH_REMATCH[1]}

$string is left untouched if its value is not enclosed in /.

like image 39
mklement0 Avatar answered Nov 15 '22 21:11

mklement0