Sed Command Using Variables

Query:

I tried to use a shell script to do a for loop: 

#!...bash 
for i in (5, 10, 15, 20) do; 
sed 's/bpp=64/bpp=$i/g' myfile.c > myfile2.c 
~~ 
done 

However, each time it executes, "bpp=64" becomes "bpp=$i" instead of 
"bpp=5" ...... 

How to make the $i inside sed command to be a real variable. 

Solution:

For variables double quote, for wyswyg characters single quote. Concatenate when both are present:

Code:

#if there were regular ocurrences of $ you could concatenate:

sed  's/bpp=64/bpp='"$i/g"  myfile.c  >  myfile2.c 
 

#if you only use $ for variables, just double quote:

sed  "s/bpp=64/bpp=$i/g"  myfile.c  >  myfile2.c
 

Query:

I want to use variables in a script using a sed command line. How can I do?

Imagine there's a file containing on each line a number ("2" on the first line of the file "file1"). I want to stock the number on a given line. For example I want the number of the first line. I'd like to to something like that : sed -n '1,1p' file1 but with variables, like that :

In this case, i would be equal to 1
var1=$i,$i
var2="$var1"p
sed -n 'var2' file1

How can I do that ?

Solution:

sed s/$var1/$var2/ file

this goes to stndout, so just redirect to a new file if necessary

sed s/$var1/$var2/ file > newfile
 

Query:

I would like to use 'sed' to edit a file by searching for a fixed string and replacing it with an environment variable that is dynamically set with, in this case, the current date and time.

I'm trying this format of the command:

sed 's/XXXXXX/${env_var}/' filein.txt

The command replaces the 'XXXXXX' with literally '${env_var}' and not the interpretation of the variable. I have set the variable before trying to run this command.

It appears 'sed' will only replace using literally what's between the delimiter characters.

Any way to do this?

Solution:

Change your single quotes to double quotes in your sed command. 

Double quotes allow shell expansion; single quotes protect from shell expansion.

Have a Unix Problem
Unix Forum - Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.