LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to replace line with another line in shell script (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-replace-line-with-another-line-in-shell-script-791674/)

pramod.srk 02-26-2010 03:30 AM

How to replace line with another line in shell script
 
Dear All,
I have the file abc.txt

cat abc.txt
This is a test file
Nothing is new in this world


I want to replace
"This is a test file" to "Text is replaced"

Code
Code:

FindString='This is a test file'
ReplaceString='Text is replaced'
Findarray=(`echo $FindString | tr ' ' ' '`)
ReplaceArray=(`echo $ReplaceString | tr ' ' ' '`)

# Length
num_new_items=${#Findarray[@]};

# Length of replace array
ReplaceArrayLength=${#ReplaceArray[@]};

echo "Replace Array Length : $ReplaceArrayLength"

echo "Length $num_new_items";
for (( i=0;i<$ReplaceArrayLength;i++)); do
        sed  -i s/${Findarray[$i]}/${ReplaceArray[$i]}/g TestFile
#        echo ${array[$i]};
#        echo $i;
done


But this is not effective.
Any idea how to replace entire line either using sed or awk or any other utility.

Thanks in Advance,
Pramod

evo2 02-26-2010 03:35 AM

Hi,

how about:
Code:

sed 's/This is a test file/Text is replaced/' < abc.txt > abc.txt.new;  mv abc.txt.new abc.txt
Evo2.

pramod.srk 02-26-2010 03:55 AM

Thanks for the reply.
The changes are not reflected when i tried to run the following command.

export a="This is a test file"
export b="Text is replaced"
sed 's/$a/$b/' < abc.txt > abc.txt.new; mv -f abc.txt.new abc.txt

evo2 02-26-2010 04:17 AM

The problem is that you have $a and $b between single quotes, meaning they will not expand to their variables.
Use double quotes if you want to expand shell variables. Eg
Code:

a="This is a test file"
b="Text is replaced"
sed "s/$a/$b/"  < abc.txt > abc.txt.new; mv -f abc.txt.new abc.txt

Evo2.

pramod.srk 02-26-2010 04:57 AM

It worked.. :-)

Thank you very much.

whizje 02-26-2010 06:00 AM

You can also use the -i option in place replacement
Code:

bash-3.1$ cat abc.txt
This is a test file
Nothing is new in this world
bash-3.1$ a="This is a test file";b="Text is replaced";sed -i "s/$a/$b/" abc.txt
bash-3.1$ cat abc.txt
Text is replaced
Nothing is new in this world



All times are GMT -5. The time now is 02:04 PM.