sed to replace a line with modified line in same file

i have few lines in a file... i am reading them in a while loop so a particular line is held is $line1.. consider a modified line is held in $line2.... i want to replace $line1 with $line2 in the same file... how to do it..?
i have come up till the below code

 sed "s/$line1/$line2/g" tmpfile.sql

the code replaces fine but its not replaced in same file..it just displays it, i could direct to another temporary file but i wast the replacement to be in same file... plz help..

sed -i , or use a temporary file and move it afterwards.

1 Like

cat input:

hello
world
sed -i 's/world/earth/g' input

cat input:

hello
earth

thanks it worked :slight_smile:

---------- Post updated at 05:56 PM ---------- Previous update was at 05:39 PM ----------

oh am sorry it dint work....
here what i tried...
contents of tmpfile.sql is

CREATE TABLE `ZoneVoiceRecorderVoiceRecordersMap` (
  `zoneId` int(11) DEFAULT NULL,
  `voiceRecordersId` int(11) DEFAULT NULL,
  `lastModified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY `zoneId` (`zoneId`,`voiceRecordersId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

the code which i used is

while read line1
do
 if [[ `expr match "$line1" ".*DEFAULT NULL.*"` != "0" ]]; then
                line2="blah blah blah"
                sed -i 's/$line1/$line2/g' tmpfile.sql
        fi
done < tmpfile.sql

i am not getting any error but when i open tmpfile.sql its not changed....

Use double quotes with sed if you have variables inside...

sed -i "s/$line1/$line2/g" tmpfile.sql

--ahamed

1 Like

Oh thanks.. its working now... :slight_smile: