I have the below text in a file


I want to replace the above text with the below text using sed


Where version is a variable.

How can we do this?

  • are $path_opt and $path_track also variable that should be expanded? – RomanPerekhrest Jul 3 '17 at 15:09
  • yes, they are defined in the file – sap Jul 3 '17 at 15:10
  • Try sed -i 's/path_tryuio=$path_opt//GMT//$CARGMT_VERSION/path_tryuio=$path_track//GMT//cayu//station//GMT//$CARGMT_VERSION/g' * – Amit24x7 Jul 3 '17 at 15:10
  • can we put the strings in a variable and then use it in sed? – sap Jul 3 '17 at 15:11

Since the path contains slashes, you probably don't want to use the common / character as the delimiter for sed. Here, instead of using / I use ^:

$ echo $path_tryuio
$ echo $path_tryuio | sed -e "s^/is^^"

Also note the use of double quotes instead of single quotes – the shell does not expand variables within single quotes.


Assuming you wanted the following modifed


and not what's on the right of = as is normally to be expected, you can achieve this using sed as:

sed -e 's|path_tryuio=$path_opt/\(GMT/$CARGMT_VERSION\)|$path_track/GMT/cayu/station/\1|'

Note that in the above sed command what we have are single quotes, so the $ variables will not interpolated, rather as literal strings.

The $ in $path_opt won't be treated as end of pattern space, since there is text after it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.