Solved: Replace a line in a file with shell

Bash shell is the common linux command language.
Post Reply
mister_v
Posts: 188
Joined: Thu Mar 04, 2010 9:19 pm

Solved: Replace a line in a file with shell

Post by mister_v »

Hi,

I would like to replace (part of) a line in a file,
using a shell script

I know how to add a line, simply echo test >> file

But how do I replace a specific line, without touching anything else?


thanks
chris
Site Admin
Posts: 194
Joined: Mon Jul 21, 2008 9:52 am

Re: Replace a line in a file with shell

Post by chris »

You can use sed
It is a very useful program with lots of option (Check the man page > man sed)

Code: Select all

sed -i "s/12345678/${REPLACE}/g" $FILE
this replaces the string 12345678 with the contents of variable $REPLACE in the file $FILE.
the -i option let you edit the file

But if you want to replace a line, and you only know part the line.
Like you want to update a variable
You can use this code

Code: Select all

sed -i "s/\(variable=\).*/\1${NEWVALUE}/g" $FILE
\(variable=\).* searches for a line that starts with variable=
\1 tells to also write the first part (variable= in this case)
and the the new value $NEWVALUE

Hopes this is what you are searching for.
mister_v
Posts: 188
Joined: Thu Mar 04, 2010 9:19 pm

Re: Solved: Replace a line in a file with shell

Post by mister_v »

Thanks that is exactly what I needed :D
Post Reply