Tuesday, July 10, 2012

How to replace portions of a unix path with sed

Sometimes you need to replace part of a pathname with a substitution. For example, you might want to change /my/old/path to /this/new/path.

Doing this with the typical delimiter '/' can look pretty ugly due to escape characters:

$ echo /my/old/path | sed 's/\/my\/old\/path/\/this\/new\/path/g' 
/this/new/path 

However this looks much cleaner by changing delimiter, the char after 's':

$ echo /my/old/path | sed 's|/my/old/path|/this/new/path|g'
/this/new/path

2 comments:

  1. Thanks!
    can you tell why did i got the below?


    sed -i 's|/$EASY_RSA/keys/|/etc/openvpn/keys/g' /etc/openvpn/easy-rsa/2.0/vars
    sed: -e expression #1, char 38: unterminated `s' command

    ReplyDelete
  2. You are mising the closing |:
    sed -i 's|/$EASY_RSA/keys/|/etc/openvpn/keys/|g' /etc/openvpn/easy-rsa/2.0/vars

    ReplyDelete