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.
`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.
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.
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}
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 /
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With