Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable with sed in Shell Script

Tags:

shell

sed

I'm writing a shell script to edit Change-Set attributes of aegis. The command I'm using is:

aegis -Change_Attributes -Edit

which opens up a vi editor to carry out the changes. I want to do a search and replace:

s/brief_description \= \"none\"\;/brief_description \=

\"test\"/g

Can I pass these directly to the open vi instance via the script without typing in any of it? I want to save the document (:wq) after editing it.

P.S. The file is a temporary file created when executing the command so I don't know the original path

Edit: I could used sed in this case:

sed -e 's/brief_description\ \=\ \"none\"\;/brief_description\ \=\

\"test\"\;/g'

The solution (inelegant hack??) would be to "cat" the output from aegis (setenv VISUAL cat), modify the out put stream with the above command and save it to a temp file, and use :

aegis -change_attributes -file <temp file>

EDIT2: I've almost got it to work. But there's a problem with the way I use sed

I have the following line in my script:

sed -i 's/brief_description\ \=\ \"none\"\;/brief_description\ \=\ \"${DESC}\"\;/g' temp_next.txt

But the $DESC variable does not evaluate to its value and the out put is given as:

brief_description = "${DESC}";

How can I pass DESC to sed that it would evaluate to it's actual value?

EDIT3:

Using

sed -i 's%brief_description\ \=\ \"none\"\;%brief_description\ \=\ \"'"$DESC"'\"\;%g' temp_next.txt

worked. I replace the normal delimiter (/) with % and put the environment variable in double quotes.

like image 633
Gayan Avatar asked May 08 '26 03:05

Gayan


1 Answers

You don't need to know the path - the aegis app will supply that. You need to change the environment variable that specifies what editor aegis uses to point at a script, and in that script use the sed stream editor to perform your edits.

Edit: Regarding your variable name expansion problem, change the set of single quotes enclosing the whole sed substitution expression to double quotes. Variable substitution is turned off by single quotes.