Solved Variable use in SED

November 16, 2014 at 23:19:22
Specs: Windows 7
Hi All,

I am trying to use a dynamic variable in SED, but not getting correct output. Please help me on this issue. Below is my script.

#!/bin/ksh
for i in `cat fields.txt`
do
var1=^"${i}"*
echo "var1 value : " ${var1}
sed -n -e '/${var1}/p' input #Not getting response on this line
sed -n -e '/${var1}/p' input >> out # Not getting response on this line
sed 's/^var1*/BOOTSTRAP_PORT_NUMBER=2000/g' input > output.txt
done

fields.txt
BOOTSTRAP_PORT_NUMBER
Test

input:
BOOTSTRAP_PORT_NUMBER=2001
testing
sed example

Not getting output at these two lines in the above script.
sed -n -e '/${var1}/p' input #Not getting response on this line
sed -n -e '/${var1}/p' input >> out # Not getting response on this line

Static Example ( It is working fine ) :
sed -n -e '/^BOOTSTRAP_PORT_NUMBER*/p' input

Regards,
Raja Sekhar


See More: Variable use in SED

Report •

#1
November 17, 2014 at 16:34:15
When embedding shell variables in a sed script, the variable must be surrounded with quotes:

while read i
do
var="^${i}*"
sed -e '/"$var{i}"/p' input
done < fields.txt


Finally instead of using for i in `cat fields.txt`, use the while loop. If you want to know why, check out this link:

http://www.smallo.ruhr.de/award.html

message edited by nails


Report •

#2
November 17, 2014 at 20:16:20
Hi Nails,
I tried with your solution, still have the issue. I am trying to filter out the matching records from input file and store in out file.

#!/bin/ksh
while read i
do
var="^${i}*"
echo " var : " "$var"
sed -n -e '/"$var"/p' input >> out
sed -n -e '/^BOOTSTRAP_PORT_NUMBER*/p' input >>out2
done < fields.txt


No response at this line :
sed -n -e '/"$var"/p' input >> out


Regards,
Raja Sekhar


Report •

#3
November 18, 2014 at 07:45:01
✔ Best Answer
Try this:

sed -n -e "/`echo ${var}`/p" input >> out

Note that I am using command substituion to echo the contents of the variable within the sed command so I am using the back tic character around the echo:

`echo ${var}`

Using ksh, this also works:

sed -n -e "/$(echo ${var})/p" input >> out

message edited by nails


Report •

Related Solutions

#4
November 18, 2014 at 18:28:53
It is working fine. Thank you very much Nails.

Report •

Ask Question