Search code examples
linuxbashshellsedrhel6

Replacing sed with sed on RHEL6.7


I am trying to replace a sed command with a sed command and it keeps falling over so after a few hours of "picket fencing" I thought I would ask the question here.

I have various bash scripts that contain this kind of line:

 sed 's/a hard coded server name servername.//'

I would like to replace it with:

 sed "s/a hard coded server name $(hostname).//"

Note the addition of double quotes so that the $(hostname) is expanded which make this a little trickier than I expected.

So this was my first of many failed attempts:

cat file | sed 's!sed \'s\/a hard coded server name servername.\/\/\'!sed \"s\/a hard coded server name $(hostname).\/\/\"!g'

I also tried using sed's nice "-e" option to break down the replace into parts to try and target the problem areas. I wouldn't use the "-e" switch in a solution but it is useful sometimes for debugging:

cat file | sed -e 's!servername!\$\(hostname\)!' -e 's!\| sed \'s!\| sed \"s!'

The first sed works as expected (nothing fancy happening here) and the second fails so no point adding the third that would have to replace the closing double quote.

At this point my history descends into chaos so no point adding any more failed attempts.

I wanted to use the first replacement in a single command as the script is full of sed commands and I wanted to target just one specific command in the script.

Any ideas would be appreciated.


Solution

  • Here's how you could do it in awk if you ignore (or handle) metachars in the old and new text like you would with sed:

    $ awk -v old="sed 's/a hard coded server name servername.//'" \
          -v new="sed 's/a hard coded server name '\"\$(hostname)\"'.//' \
              '{sub(old,new)}1' file
    sed 's/a hard coded server name '"$(hostname)"'.//'
    

    or to avoid having to deal with metachars, use only strings for the comparison and replacement:

    $ awk -v old="sed 's/a hard coded server name servername.//'" \
          -v new="sed 's/a hard coded server name '\"\$(hostname)\"'.//'" \
              's=index($0,old){$0=substr($0,1,s-1) new substr($0,s+length(old))}1' file
    sed 's/a hard coded server name '"$(hostname)"'.//'