replace last / by |

Hi:

I want to write a Kshell script which will replace last / by |.

eg: /home/apps/test/document should be replaced as /home/apps/test|document.

The length of the string is not constant.

Thanks,
Ash

# echo "/home/apps/test/document" | sed 's/^\(.*\)\/\(.*\)/\1\|\2/'
/home/apps/test|document
sed 's_/\([^/]+\)$_|\1_'

Hi.

I needed to use "*" instead of "+". Some versions of sed may need "-r" to use extended regular expressions, in which the parens also need to modified:

#!/bin/sh -

# @(#) user2    Demonstrate replacement of last specific character, sed.

sed --version | head -1

echo
echo " Original:"
echo "/home/apps/test/document" |
sed 's_/\([^/]+\)$_|\1_'

echo
echo " Modified:"
echo "/home/apps/test/document" |
sed 's_/\([^/]*\)$_|\1_'

echo
echo " Original with -r:"
echo "/home/apps/test/document" |
sed -r -e 's_/([^/]+)$_|\1_'

exit 0

Producing:

% ./user2
GNU sed version 4.1.2

 Original:
/home/apps/test/document

 Modified:
/home/apps/test|document

 Original with -r:
/home/apps/test|document

There are (too) many versions of sed, so one must know which version one is using. For example, if you were to leave the "\(", "\)" in the 3rd example, you would get an error message, "invalid reference \1", not very informative, at least not directly ... cheers, drl

Actually, what I intended to post was this, but got distracted by an awk script:

sed 's_/\([^/][^/]*\)$_|\1_'

If you mean something followed by at least one other character, be explicit.

cr=$(echo /tutu/tatat/titi/tutu | awk -F/ '{ print $NF; }')
echo /tutu/tatat/titi/tutu | sed -e 's/\/'$cr'$/|'$cr'/'
/tutu/tatat/titi|tutu

Hi guyz:

Thank you for your help. Esp Reborg, i used your suggestion, and it works perfectly well.

Thanks!