tags:

views:

43

answers:

1

Hi all

How to replace the

<x>

with word Before_last_dir only on the dir that located before the last dir (according to this example – dir4)

 echo "/dir1/dir2/dir3<x>/dir4<x>/dir5<x>" |sed s"/<x>/Before_last_dir/g"

Another example

echo "/dirA<x>/dirB<x>/dirC<x> >" |sed s"/<x>/Before_last_dir/g" 

should be

/dirA<x>/dirBBefore_last_dir/dirC<x>
+2  A: 
$ echo "/dir1/dir2/dir3<x>/dir4<x>/dir5<x>" | sed -E "s/<x>(\/[^\/]+)$/Before_last_dir\1/g"
/dir1/dir2/dir3<x>/dir4Before_last_dir/dir5<x>

(-E means sed is using POSIX extended regular expressions)

Alternatively, without -E (as -E may not be available on some systems):

$ echo "/dir1/dir2/dir3<x>/dir4<x>/dir5<x>" | sed "s/<x>\(\/[^\/]\{1,\}\)$/Before_last_dir\1/"
/dir1/dir2/dir3<x>/dir4Before_last_dir/dir5<x>

This should work everywhere. (EDIT: changed the "+" operator to the POSIX "{1,}" since "+" is a GNU extension, not in POSIX.

imploder
-E not support on some linux
yael
@Tom: That's weird, it works for me (Linux Fedora 13) just as displayed here. It may be an issue with sed - are you using another version than GNU sed?Here: GNU sed version 4.2.1; GNU bash, version 4.1.7(1)-release (i386-redhat-linux-gnu).
imploder
@imploder: I deleted the comment because I found yours to be good.
Tom Dignan
You can reduce some of that escaping by using alternative delimiters and `g` is unecessary: `sed -E 's|<x>(/[^/]+)$|Before_last_dir\1|'`. GNU `sed` understands `-E` for compatibility, but the documented option is `-r`.
Dennis Williamson