This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

search for a word in a file and rename the word next to it

Old posts that have not been replied to for several years.
Locked
u
uTc

Post by uTc »

say the file has:
hello bob
how can i make it search the file for hello and replace bob with another word?
p
ppslim
Revered One
Posts: 3914
Joined: Sun Sep 23, 2001 8:00 pm
Location: Liverpool, England

Post by ppslim »

Code: Select all

set word1 "hello"
set word2 "bob"
set word3 "replace"
set file "blah"
file copy -force -- $file "${file}.bak"
set rfp [open "${file}.bak" r]
set wfp [open $file w]
while {![eof $rfp]} {
  set s [gets $rfp]
  while {[string match "* $word1 $word2 *" $s]} {
    set s [string replace $s [string first $word2 $s] [string wordend $s [string first $word $s]] $word3]
  }
  puts $wfp $s
}
close $wfp
close $rfp
Note, this is untested.
User avatar
stdragon
Owner
Posts: 959
Joined: Sun Sep 23, 2001 8:00 pm
Contact:

Post by stdragon »

Code: Select all

set text "let's get some sexy goats"

regsub -all -- {(^|W)(sexy) w*} $text {12 sheep} newtext

# now it's "let's get some sexy sheep"
Locked