How can I use a variable in sed?


Login or Register to Reply

 
Thread Tools Search this Thread
# 1  
Old 05-27-2004
How can I use a variable in sed?

Hi
I'm trying to change a part of a line with sed. Usually I will run
sed 's/mytext/mynewtext/'

Now I have a variable: var=mynewtext

sed 's/mytext/$var/' does not work. I have also tried to protect the $ with different characters but it still does'nt work.

I will be very happy if someone has a solution to this.
# 2  
Old 05-27-2004
For starters, you can switch to double quotes:

sed "s/mytext/$var/"

Sometimes that does not work. It would depend on the exact value of mytext. So another solution is to turn the single quoted string into two single quoted strings:

sed 's/mytext/'$var'/'

In this case, the 2nd single quoted string is '/'. Just using a backslash would work to that and it saves a character:

sed 's/mytext/'$var\/

There is actually no reason to quote a slash so this should also work with most shells:

sed 's/mytext/'$var/

And there may be no reason to quote anything at all, but again, the actual vakue of mytext determines this. So this may work:

sed s/mytext/$var/

Opps...you only wanted a solution, so I'll quit now....Smilie
These 3 Users Gave Thanks to Perderabo For This Post:
gautamsomani (04-29-2012) souvikgargi (06-26-2011) Uday Rangta (06-10-2016)
Login or Register to Reply

|
Thread Tools Search this Thread
Search this Thread:
Advanced Search

More UNIX and Linux Forum Topics You Might Find Helpful
Variable in sed OXYD UNIX for Dummies Questions & Answers 9 12-08-2015 08:27 AM
How to use the variable in sed? yanglei_fage Shell Programming and Scripting 1 11-14-2013 12:10 AM
Using variable in sed mattiasvdm OS X (Apple) 13 03-06-2013 04:41 AM
How to pass value of pwd as variable in SED to replace variable in a script file cielle Red Hat 6 03-28-2012 03:47 AM
sed and variable ade05fr Shell Programming and Scripting 2 03-07-2012 05:17 AM
sed with variable itsjoy2u Shell Programming and Scripting 2 05-06-2011 04:03 AM
sed with variable itsjoy2u Red Hat 0 05-04-2011 07:31 AM
Expand an environment variable in sed, when the variable contains a slash Ilja Shell Programming and Scripting 2 11-10-2010 10:58 AM
Insert a line including Variable & Carriage Return / sed command as Variable lowmaster Shell Programming and Scripting 2 05-20-2009 12:26 AM
using variable in sed Kochu77 Shell Programming and Scripting 3 11-22-2008 06:19 AM
Sed variable substitution when variable constructed of a directory path alrinno Shell Programming and Scripting 2 07-11-2008 03:24 PM
sed with variable mahabunta Shell Programming and Scripting 1 07-08-2008 09:16 AM
want to use variable in sed shailesh_arya Shell Programming and Scripting 3 07-07-2008 10:09 PM
sed with a variable ngagemaniac Shell Programming and Scripting 6 06-12-2008 02:35 PM
sed (variable) malaymaru Shell Programming and Scripting 13 05-07-2008 07:56 AM