We help IT Professionals succeed at work.

ksh scripting, to replace a value in a file

pal2k
pal2k asked
on
Hi,

I need a quick help...

I have a file like "server.txt"

I need a unix ksh script to replace a value in the file.
The file content is below.In the below file I need to replace the value for "server".
Like     server="windowsxyz"   replace  to    server="xyzw".


cat sever.txt
------------
#this file has config properties

hostname="servername123"
server="windowsxyz"
#

#end of line
Comment
Watch Question

Top Expert 2007

Commented:
try

sed 's/server=\"windowsxyz\"/ server=\"xyzw\"' < server.txt > server.tmp
mv server.txt server.old
mv server.tmp server.txt

Author

Commented:
thanks omarfarid,

it would be nice if i can get in script form.

and one more thing. I should be able to use the script for different files with same name as server.txt.
so while replacing,  each fils will have different values for "server" and the replacing value is constant "xyzw"

Author

Commented:
omarfarid,

also,

1)   The file name should not be disturbed or changed.

2) the value for "server" might be different in different files but file name is same server.txt

so the sed should look for only server and replace with "xyzw" with what evr value is existing.
Most Valuable Expert 2013
Top Expert 2013
Commented:
Hi,
it could look like this.
The code below will replace all that's between the double quotes following server= with "xyzw" in a file called "server.txt".

#!/bin/ksh
sed "s/server=\".*\"/server=\"xyzw\"/" server.txt > server.txt.$$
echo mv server.txt.$$ server.txt
exit

Basically we write the changed file to a temporary file, to then rename this file back to original.
I put echo in front of this final step for you to verify the results beforehand.
Some sed implementations support the "-i" (in place) flag.
You won't need an intermediate file in this case, but changes will be immediate!
#!/bin/ksh
sed -i "s/server=\".*\"/server=\"xyzw\"/" server.txt
exit
 
wmp