15

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?

4
  • Are your /s always at the beginning and the end?
    – iruvar
    Jun 13, 2014 at 18:51
  • They can be, but it isn't guaranteed. I also need to persist slashes inside the string.
    – whitfin
    Jun 13, 2014 at 18:56
  • 1
    Note that your 1st assignment as currently written (string=/this is my string/), is syntactically invalid - you need quotes around the value.
    – mklement0
    Jun 13, 2014 at 21:08
  • @mklement0 yeah was just a typo
    – whitfin
    Jun 15, 2014 at 16:16

6 Answers 6

27

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}
4
  • How is this an answer to the question exactly? This does exactly what the question already suggests, but they explicitly ask for a solution in a single statement. This just copies the problem statement.
    – Pankrates
    Dec 13, 2022 at 7:51
  • Because it states that it can't be done in a single statement, but it's much lighter weight than any of the piping solutions. It also works when either of the slashes is missing.
    – Stormcloud
    Dec 15, 2022 at 9:47
  • Output in the second code block is wrong. The output column two should always be one/two Nov 20, 2023 at 17:48
  • @austinheiman - point noted and fixed. I think it was something that got missed in the editing. Thank you.
    – Stormcloud
    Nov 22, 2023 at 9:55
5

Unfortunately there's no way to do that. However if you're sure that your string begins in / and ends in / you can trim it by ${P:M:N} format:

string='/this is my string/'
string=${string:1:(-1)}

Adding a check could also help but it's still two statements:

[[ $string == /*/ ]] && string=${string:1:(-1)}

Note: Solution is only available starting Bash 4.2.

4

If you are willing to use sed you could do:

string="/this is my string/"
echo $string | sed 's/^\/\(.*\)\/$/\1/g'

This assumes the slashes are at the beginning and/or end of the string

4
  • Nice, and it should persist slashes within the string right? Is this the fastest method?
    – whitfin
    Jun 13, 2014 at 18:57
  • It only strips slashes at the beginning ^ operator and at the end $ operator. If it is the fastest I don't know, you should test this yourself
    – Pankrates
    Jun 13, 2014 at 19:00
  • 3
    fastest is going to be the two lines in the question itself. Avoid forks. Anyway: res=$(echo "/what ever/" | sed 's@^/@@;s@/$@@') -- avoid the backslashes, too.
    – Bruce K
    Jun 13, 2014 at 19:14
  • 3
    @Zackehh9lives If you can do string=${string%/}; string=${string#/} you better choose it over sed It's way faster than forking and piping. Also this is still a two statement process.
    – konsolebox
    Jun 13, 2014 at 19:39
3

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 /.

2

If your /s are always at the start and end

echo "${string//\/}"
this is my string

If not

string="/this is /my string/"
IFS=/ read -ra x <<<"$string"
(IFS=/; printf '%s\n' "${x[*]:1:${#x[*]}-1}")
this is /my string

Or

echo "$(IFS=/; set -- $string; printf '%s\n' "${*:2:$#-1}")"
this is /my string
1
  • 1
    ${string//\/} removes all the slashes, not the leading or trailing.
    – eexit
    Dec 15, 2021 at 11:12
-1
#!/bin/bash
truncate_leadingSlash()
{
 local string="$1"
 local len=${#string}
 while [[ "${string:$(expr $len - 1)}" == "/" ]]
 do
  string=${string:0:$(expr $len - 1)}
  len=${#string}
 done
 echo $string
}

truncate_leadingSlash "Autobiography/Of/Yogi//////"

Output: "Autobiography/Of/Yogi"

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.