SED:: Using variable while grouping

Hi,
I have the following script :-

#!/bin/csh -f
set var="HOST2"
sed -e 's/\(.*TRANSFER TO\).*\(usr\)/\1 "$var" \2/' tempFile
 

tempFile contains:

STOP TRANSFER TO HOST1             /usr/bin/myscript
  1. How to use variable in the above sed command. It replaces with $var instead of HOST2

  2. In the second grouping while replacing, the "/" from usr is gone, how to handle that?

Thanks

Try

sed -e "s/\(.*TRANSFER TO\).*\(\/usr\)/\1 $var \2/"

To "translate" $var into it's value
To also pick the slash "/" from usr

1 Like

Thanks AGAIN to you for solving my issue :slight_smile:

No problem. You're welcome. I'm glad it worked :slight_smile:

Hi,
One issue here.
This line

STOP TRANSFER TO HOST1             /usr/bin/myscript

is like this

"STOP TRANSFER TO HOST1"             /usr/bin/myscript

So, the sed command removes the closing quotes. How do I preserve that ?

sed -re "s|(.*TRANSFER TO +).*(\"? +(/usr)|\1$var\2|"

in this case, i use extended regexp (sed -re)
The first set of parenthesis goes from the beginning of the line to TRANSFER TO including following spaces (...TO +).
The second set goes from a possible quote (\"?) to /usr including spaces in between.
Ask me if it's not clear

sed "s|\(TRANSFER TO\).*\"|\1 $var\"|"