Page 1 of 1

replace a string in a file and then save file with new name

Posted: 29 Aug 2011 07:33
by goreilly
Hello, I'm a newbee. Simple question.

How do I open a text file, find a particular string, replace that string with another string, and then save the file with a new name.
So far, I can find the string in a file using the find command, but then I don't know how to replace the string in that file.

Thank you,
Gerry :D

Re: replace a string in a file and then save file with new n

Posted: 29 Aug 2011 19:50
by InterociterOperator
What if we save the file with a new name and THEN replace a string? :)

I would cheat and program in Edlin, which has been part of DOS since the beginning.

Make a copy of your original file with a copy command and work from it.

Code: Select all

copy Members.txt Names.txt


Now say we want to find "Harry" in our new file called Names.txt, and change it to "Mary" ...

If Names.txt contains:
Tom
Dick
Harry

and NewName.txt contains
Mary

..we could do...

Edlin c:\Names.txt < c:\EdlinCommands.txt

where the EdlinCommands file contains...

Code: Select all

1sHarry
.d
.tNewNames.txt
e


"1sHarry" means start at the first line in the file and search for the word Harry
and ".d" means delete the line that contains "Harry"
and ".tNewName.txt" means transfer the contents of "NewName.txt" to this line location (.).
"e" means save and end.

Re: replace a string in a file and then save file with new n

Posted: 29 Aug 2011 21:18
by Ocalabob
Greetings Gerry!

If SED is an optional then the solution is trivial. Here's a SED
routine within a batch file as an example for your consideration.

[code]
@echo off
::Create a test file
echo Now is the time for all good men to come to the aid of their Country.>$$$Gerry.txt

::Use SED to replace some text.
type $$$Gerry.txt |SED "s/men/men and women/g" |SED "s/Country./State./g">$$$Gerry_final.txt
echo Orginal Line is:
type $$$Gerry.txt
echo.
echo Replaced line is:
type $$$Gerry_final.txt
echo.
echo Press The Space Bar to Close this Window.
pause>nul
::Housekeeping
del $$$*.txt
[code]

Best wishes Gerry!

Re: replace a string in a file and then save file with new n

Posted: 29 Aug 2011 22:08
by ghostmachine4
[quote="Ocalabob"]

Code: Select all

::Use SED to replace some text.
type $$$Gerry.txt |SED "s/men/men and women/g" |SED "s/Country./State./g">$$$Gerry_final.txt


No need to use type, since sed takes in a file as argument. And you can combine sed commands together

Code: Select all

sed "s/men/blah blah/g;s/Country/blah blah ../g" Gerry.txt

Re: replace a string in a file and then save file with new n

Posted: 30 Aug 2011 12:09
by goreilly
Responders:
Thank you so much. I downloaded sed and ran the suggested programs, and they did the trick most effectively.
Save me a lot of time struggling with dos stuff.
Gerry :D :D