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
-
echo 'param="/var/tmp/test"' | sed 's/\/[^\/]*"/\/REPLACEMENT"/' param="/var/tmp/REPLACEMENT" echo '/var/tmp/test' | sed 's/\/[^\/]*$/\/REPLACEMENT/' /var/tmp/REPLACEMENTyael : and if I want only to get the test word? yaelzed_0xff : Sorry, I'm not sure I understand what you mean by "get the test word" -
You don't need
sedfor this...basenameanddirnameare a better choice for assembling or disassembling pathnames. All those escape characters give me a headache....param="/var/tmp/test" param_repl=`dirname $param`/newtestyael : please see the follwoing error by sed I need to use the " in order to set the $DIRNAME DIRNAME=/var/tmp echo /var/tmp/test| sed "s/\/[^\/]*$/\/BACKUP.DIR.$DIRNAME/g" sed: -e expression #1, char 27: Unknown option to `s'Jim Lewis : Yup, that's an error all right. To fix it, use something other than sed. :-) -
Extracting bits and pieces with
sedis a bit messy (as Jim Lewis says, usebasenameanddirnameif you can) but at least you don't need a plethora of backslashes to do it if you are going thesedroute 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
sedcontrol script:$ echo 'param="/var/tmp/test"' | sed ' s!.*/!! ; s/"$// ' testyael : please explain --> sed ' s!.*/!! ; s/"$// syntax THXDonal Fellows : @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`. -
It's not clear whether
paramis 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}"yael : OK but also I need explain about sed ' s!.*/!! ; s/"$// syntax how it work?
0 comments:
Post a Comment