Thursday, April 28, 2011

Replacing the last word of a path using sed.

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

From stackoverflow
  • echo 'param="/var/tmp/test"' | sed 's/\/[^\/]*"/\/REPLACEMENT"/'
    param="/var/tmp/REPLACEMENT"
    
    echo '/var/tmp/test' | sed 's/\/[^\/]*$/\/REPLACEMENT/' 
    /var/tmp/REPLACEMENT
    
    yael : and if I want only to get the test word? yael
    zed_0xff : Sorry, I'm not sure I understand what you mean by "get the test word"
  • 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
    
    yael : 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 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
    
    yael : please explain --> sed ' s!.*/!! ; s/"$// syntax THX
    Donal 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 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}"
    
    yael : OK but also I need explain about sed ' s!.*/!! ; s/"$// syntax how it work?

0 comments:

Post a Comment