Skip to content

Remove appending slash from a path using Sed

Here’s how you can remove the appending slash from a path using sed, the stream editor:

echo /just/a/path/ | sed -e 's#/$##'
# Output: /just/a/path
 
# And, if there isn't an appending slash, nothing happens:
 
echo /just/another/path | sed -e 's#/$##'
# Output: /just/another/path 

It works quite simple. Sed executes expression (-e) on its standard input. The expression is a substitution using regular expressions. The #-sign is the delimiter. The part (#/) between the first two hash signs is the matching expression and the (empty) part between the second and the third hash sign is the replacement expression. This expression (“s#/$##”) basically says: replace all occurrences of “/” at the end of the line (the dollar sign is the end-of-line anchor) with nothing.

To use this in a script is easy-peasy. Suppose $1 is a system path that may or may not include an appending slash:

#!/bin/bash
 
sanitized_path=`echo "$1" | sed -e 's#/$##'`
 
echo $sanitized_path

This script outputs its first parameter with the appending slash removed.


    No Comments ( Add comment / trackback )