sed: Removing trailing "/"

Can somebody provide me with a sed command that will remvove a
trailing slash.

For example if I have this /tmp/one/two/three/ I want to make it /tmp/
one/two/three

Thanks in advance for all that answer this post
stu [ Do, 06 Dezember 2007 22:17 ] [ ID #1886796 ]

Re: sed: Removing trailing "/"

Stu wrote:
> Can somebody provide me with a sed command that will remvove a
> trailing slash.
>
> For example if I have this /tmp/one/two/three/ I want to make it /tmp/
> one/two/three

$ echo "/tmp/one/two/three/" | sed "s,/$,,"
/tmp/one/two/three

--
Best regards | Be nice to America or they'll bring democracy to
Cyrus | your country.
Cyrus Kriticos [ Do, 06 Dezember 2007 22:25 ] [ ID #1886797 ]

Re: sed: Removing trailing "/"

At 2007-12-06 04:17PM, "Stu" wrote:
> Can somebody provide me with a sed command that will remvove a
> trailing slash.
>
> For example if I have this /tmp/one/two/three/ I want to make it /tmp/
> one/two/three

If you really want sed:
x="/tmp/one/two/three/"
echo "$x" | sed -e 's,/$,,'

However, it would be more efficient to let your shell do it -- in bash
(and I'm sure many other shells): echo "${x%/}"

--
Glenn Jackman
"You can only be young once. But you can always be immature." -- Dave Barry
Glenn Jackman [ Do, 06 Dezember 2007 22:27 ] [ ID #1886798 ]

Re: sed: Removing trailing "/"

On 6 Dec 2007 21:27:39 GMT, Glenn Jackman wrote:
> At 2007-12-06 04:17PM, "Stu" wrote:
>> Can somebody provide me with a sed command that will remvove a
>> trailing slash.
>>
>> For example if I have this /tmp/one/two/three/ I want to make it /tmp/
>> one/two/three
>
> If you really want sed:
> x="/tmp/one/two/three/"
> echo "$x" | sed -e 's,/$,,'
>
> However, it would be more efficient to let your shell do it -- in bash
> (and I'm sure many other shells): echo "${x%/}"

That's a POSIX feature. So, you'll find it in any standard sh.
Only the Bourne shell and early versions of the Almquist shells
(BSD shells) do not support it.

A problem with those approaches is that it doesn't work
correctly if the input is "/". (and the usage of "echo" makes it
unreliable). The sed approach doesn't work correctly with
filenames containing newline characters.

One can also use expr:

expr "x$x" : 'x\(.*\)/'

which suffers from the same problem wrt x=/

case $x in
(*[!/]*/)
y=${x##*[!/]}
y=${x%"$y"} ;;
("") y= ;;
(*) y=/ ;;
esac

would remove every trailing /.

You can also do:

printf '%s\n' "$x" | sed '
s,//*,/,g
$!b
1{
/^\/$/q
}
s,/$,,'

Which will additionaly reduce every sequence of / to a single
one.

--
Stephane
Stephane CHAZELAS [ Fr, 07 Dezember 2007 08:59 ] [ ID #1887685 ]
Linux » comp.unix.shell » sed: Removing trailing "/"

Vorheriges Thema: insert new line
Nächstes Thema: Finding largest files on a filesystem