Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable 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?

like image 855
user788171 Avatar asked Jun 21 '12 20:06

user788171


People also ask

Can we use variables in sed command?

First, choose a delimiter for sed's s command. Let's say we take '#' as the delimiter for better readability. Second, escape all delimiter characters in the content of the variables. Finally, assemble the escaped content in the sed command.

How do you call a variable in sed command?

Use double quotes so that the shell would expand variables. Use a separator different than / since the replacement contains / Escape the $ in the pattern since you don't want to expand it.

How do you replace a variable in a file using sed?

How SED Works. In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well. Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.

Can you echo a variable?

Using the echo command you can display the output of a variable or line of text. It requires no formatting while implementing this option. The echo command is useful to display the variable's output especially when you know the content of a variable will not cause any issue.


Video Answer


1 Answers

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.

like image 69
c00kiemon5ter Avatar answered Sep 19 '22 04:09

c00kiemon5ter