Search code examples
bashvariablessedescaping

Use a variable's value in a sed command


I can't seem to use a variable in a sed command, for example:

sed "24s/.*/"$ct_tname"/" file1.sas > file2.sas

I want $ct_tname the variable, not literally $ct_tname, which is what I keep getting.

Anybody know how to get this to work?

The problem is actually more complex and I omitted some information.

ct_fname="%let outputfile="/user/ct_"$1".csv";"

Here, $1 is the argument passed in at the start of my bash script (sed is being run inside a bash script).

This doesn't run successfully, but it does run if I replace ct_fname with

ct_fname="%let table=ct_$1;"

Is there a way to get the first ct_fname to be passed successfully?


Solution

  • you need to use double quotes (") instead of single quotes ('). single quotes pass their content literally, without translating variables (expansion).

    try

    sed "24s/.*/\"$ct_tname\"/" file1.sas > file2.sas
    

    btw, if you're going to be editing a file (that is if file2.sas is a temporary file), you should be using ed instead.