0

In csh, I have a variable called $var and I want to include it in a csh script as follows

#!/bin/csh

set var="directory"
sed 's/DIRECTORY_PATH/$var1234/' > output.txt

I want the sed statement to evaluate to 's/DIRECTORY_PATH/directory1234', but instead it just tries to a lookup a variable called var1234. What's the right way to do this?

andrew
  • 2,524
  • 2
  • 24
  • 36

1 Answers1

2

Use double quotes to have the var expanded in the sed command:

set var="directory"
sed "s/DIRECTORY_PATH/${var}1234/" > output.txt
    ^                            ^

Note the usage of braces in ${var}1234: it makes bash understand the variable is $var and 1234 is text, so you can refer to the variable name concatenated with some string.

Example

$ var="me"
$ new_var="you"

$ echo "hello me" | sed 's/$var/$new_var/g' # <-- single quotes
hello me                                    # <-- no substitution

$ echo "hello me" | sed "s/$var/$new_var/g" # <-- double quotes
hello you                                   # <-- substitution!
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Thanks for the response, but it doesn't fully address the question. Suppose I wanted to replace `$var` with `$new_var` concatenated with 1234. I couldn't say `sed 's/$var/$new_var1234/g` because it would just lookup a variable called `$new_var1234` which obviously doesn't work. Do you know how I would do this? – andrew Mar 03 '14 at 15:04
  • Yes, use brackets braces --> `sed 's/$var/${new_var}1234/g`. This way, you are telling bash that the var name is just `new_var` and `1234` is just another thing. – fedorqui Mar 03 '14 at 15:14