tags:

views:

52

answers:

4

I have the following: param="/var/tmp/test" I need to replace the word test with another word such as new_test

need a smart way to replace the last word after "/" with sed

+1  A: 
echo 'param="/var/tmp/test"' | sed 's/\/[^\/]*"/\/REPLACEMENT"/'
param="/var/tmp/REPLACEMENT"

echo '/var/tmp/test' | sed 's/\/[^\/]*$/\/REPLACEMENT/' 
/var/tmp/REPLACEMENT
zed_0xff
and if I want only to get the test word?yael
yael
Sorry, I'm not sure I understand what you mean by "get the test word"
zed_0xff
A: 

You don't need sed for this...basename and dirname are a better choice for assembling or disassembling pathnames. All those escape characters give me a headache....

param="/var/tmp/test"
param_repl=`dirname $param`/newtest
Jim Lewis
please see the follwoing error by sedI need to use the " in order to set the $DIRNAMEDIRNAME=/var/tmpecho /var/tmp/test| sed "s/\/[^\/]*$/\/BACKUP.DIR.$DIRNAME/g"sed: -e expression #1, char 27: Unknown option to `s'
yael
Yup, that's an error all right. To fix it, use something other than sed. :-)
Jim Lewis
A: 

Extracting bits and pieces with sed is a bit messy (as Jim Lewis says, use basename and dirname if you can) but at least you don't need a plethora of backslashes to do it if you are going the sed route since you can use the fact that the delimiter character is selectable (I like to use ! when / is too awkward, but it's arbitrary):

$ echo 'param="/var/tmp/test"' | sed ' s!/[^/"]*"!/new_test"! '
param="/var/tmp/new_test"

We can also extract just the part that was substituted, though this is easier with two substitutions in the sed control script:

$ echo 'param="/var/tmp/test"' | sed ' s!.*/!! ; s/"$// '
test
Donal Fellows
please explain --> sed ' s!.*/!! ; s/"$// syntaxTHX
yael
@yael: It's two separate substitutions, separated by a semicolon. The second just removes a trailing `"`. The first uses an alternate syntax separator (`!`) matches the *maximal* number of characters up to a `/` (i.e. from the beginning up to the last such character) and replaces with the empty string. We know that it's maximal because the RE engine matches greedily. Remove everything up to the last slash and any trailing quote, and you've got `test`.
Donal Fellows
A: 

It's not clear whether param is part of the string that you need processed or it's the variable that holds the string. Assuming the latter, you can do this using only Bash (you don't say which shell you're using):

shopt -s extglob
param="/var/tmp/test"
param="${param/%\/*([^\/])//new_test}"

If param= is part of the string:

shopt -s extglob
string='param="/var/tmp/test"'
string="${string/%\/*([^\/])\"//new}"
Dennis Williamson
OK but also I need explain about sed ' s!.*/!! ; s/"$// syntax how it work?
yael