sed + replace word on directory PATH
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>
$ 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.
精彩评论