Question on sed

How does sed substitutes a string of characters in a file and replace it with a string passed as an argument to a variable in a script and saves the file with the changes.
Say for example

read name
sed 's/string1/$name/g filename

BTW I am using /bin/sh

kamaraj@kamaraj-laptop:~$ value="A"
kamaraj@kamaraj-laptop:~$ echo $value
A
kamaraj@kamaraj-laptop:~$ echo "kamaraj" | sed -e "s/a/$value/g"
kAmArAj
kamaraj@kamaraj-laptop:~$ 

1 Like

So the answer is use double quotes to expand the shell variable.

BTW no need to use the -e option for a single sed command.

1 Like

Just to get my concept straight about variable values replaced by sed- I have written this script not the most efficient one but works.

#!/bin/sh
echo "Enter your name \c"
read name
echo "This is the story about $name "
echo "There  is a file created for you by the name of $name.history"
touch $name.history
cp anyone $name.history
anyname=$name
sed -e s/anyname/$anyname/g $name.history > $name1.history
mv $name1.history $name.history
#!/bin/sh
echo "Enter your name \c"
read name
echo "This is the story about $name "
echo "There  is a file created for you by the name of $name.history"
touch $name.history

cp anyone $name.history  
# I guess you want to add some contents in the file
# so you should use this command: 
# echo "anyone" > $name.history

anyname=$name

sed -e s/anyname/$anyname/g $name.history > $name1.history
mv $name1.history $name.history

# Above two commands can be replaced by sed -i, if your sed support -i option.
# sed -i s/anyone/$anyname/g $name.history
1 Like