Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to remove a trailing slash from each parameter?

People also ask

How do I get rid of trailing slash?

Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.

How do I get rid of trailing slashes in Python?

The most common approach is to use the . rstrip() string method which will remove all consecutive trailing slashes at the end of a string.

How do you remove the last slash from a string in Java?

replaceAll("/","");

How do I get rid of trailing slash in WordPress?

To do so, go to the “Settings -> Permalinks” section and, depending on your situation, either add or delete the last slash. The “Custom Structure” field ends with a slash, so all other WordPress URLs will have the trailing slash.


You can use the ${parameter%word} expansion that is detailed here. Here is a simple test script that demonstrates the behavior:

#!/bin/bash

# Call this as:
#   ./test.sh one/ two/ three/ 
#
# Output:
#  one two three

echo ${@%/}

The accepted answer will trim ONE trailing slash.

One way to trim multiple trailing slashes is like this:

VALUE=/looks/like/a/path///

TRIMMED=$(echo $VALUE | sed 's:/*$::')

echo $VALUE $TRIMMED

Which outputs:

/looks/like/a/path/// /looks/like/a/path

This works for me: ${VAR%%+(/)}

As described here http://wiki.bash-hackers.org/syntax/pattern

May need to set the shell option extglob. I can't see it enabled for me but it still works


realpath resolves given path. Among other things it also removes trailing slashes. Use -s to prevent following simlinks

DIR=/tmp/a///
echo $(realpath -s $DIR)
# output: /tmp/a

FYI, I added these two functions to my .bash_profile based on the answers found on SO. As Chris Johnson said, all answers using ${x%/} remove only one slash, these functions will do what they say, hope this is useful.

rem_trailing_slash() {
    echo "$1" | sed 's/\/*$//g'
}

force_trailing_slash() {
    echo "$(rem_trailing_slash "$1")/"
}

In zsh you can use the :a modifier.

export DIRECTORY='/some//path/name//'

echo "${DIRECTORY:a}"

=> /some/path/name

This acts like realpath but doesn't fail with missing files/directories as argument.