Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace only one pattern of a line in a file using Awk or Sed? 1

Status
Not open for further replies.

micotao

Programmer
Jun 16, 2004
33
CN
Hi,
I want to only replace one pattern in specified line of one file.The file may contains many lines,the line containing the pattern 'http:' is:
ServerResourceURL DN=I want to replace nwp001--->pwd003, only in the line containing the 'http:' pattern, and leave other lines which contains nwp001 unchanged/un-replaced,i.e., the above line will be this:
ServerResourceURL DN=So after replacement,The file will be updated, all other lines(including those contain 'nwp001' but not contain 'http:') will remain unchanged, only this line with 'http:' is replaced by pwd003.
Thanks very much! It is blocking my testing!!
Suppose the file to be updated is named "file_forsed"
I use this statement, but always report syntax error,
I don't know how to fix this issue??
#!/bin/ksh

item=./file_forsed
crtfile=`basename ${item}`
old_host="nwp001"
new_host="pwd003"
cp ${item} ./${crtfile}.tmp.$$
cat ./${crtfile}.tmp.$$ | awk '/http:/ { Line=$0; Line1=$(echo $Line | sed "s/${old_host}/${new_host}/g";next} {print $0 }' > ./tmp_${crtfile}
rm -f ./${crtfile}.tmp.$$ 2>> ./elog
exit 0



Thanks again!
 
This is not tested but try something like this

Code:
awk -v h1=$old_host -v h2=$new_host  '/http:/ {sub(h1,h2)}{print}' ./${crtfile}.tmp.$$  > ./tmp_${crtfile}

CaKiwi
 
Why not simply sed ?
sed "/http:/s!${old_host}!${new_host}!" ./${crtfile}.tmp.$$ > ./tmp_${crtfile}

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top