Search code examples
unixcsh

How do you include a variable in a continuous sequence of characters


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?


Solution

  • 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!