Replacing characters in a text file with a batch file
Solution 1
The quick answer is "No, not with basic windows utilities"
But as the other answers suggested, there are lots of unix ports out there that do what you want. Take alook at gnuwin32 packages.
EDIT:
Okay, I revise my strict "No". There might be a way of doing it, depending on the complexity of your task and your OS. When using windows 2000 and above, cmd provides command extensions that you can use.
The basic idea is to use a FOR loop to go through each line of an input file and then to use string substitution provided by the SET command to replace your characters.
I have no solution at hand but you might try on your own, using infromation from this quite cool site. Look here for the FOR loop syntax and here for the string substitution.
Solution 2
you can install unxutils and then do
sed "s/WORD_FROM/WORD_TO/" file_name > changed.file.name
to change words or
cat file|tr "a" "b" > changed.file.name
to change characters
Solution 3
Use sed or nothing:
sed -i 's/FROM/TO/g' filename.txt
sed can be download here, for various platforms.
Solution 4
You have to use WIN32 SED and see the official gnu sed page for explanation. It is really powerful :
> sed "s/WORD_FROM/WORD_TO/" file_name > changed.file.name
SilverSideDown
Updated on June 19, 2022Comments
-
SilverSideDown almost 2 years
Is there a way to replace some characters in a text file with a batch file?
I didn't find any command to do that.
-
enguerran over 14 yearsGrep is used to perform search/filter... even wikipedia knows that : en.wikipedia.org/wiki/Grep
-
Deverill over 14 yearsIndeed, sed is more specific to just that task, but FYI, there are Windows/DOS variants of grep that allow replace as well.
-
Rich over 14 yearsThe basic problem with iterating over the file is that when it contains special characters such as
&
,|
or>
it gets messy. Throw in odd numbers of quotation marks in a line and all bets are off. Haven't found a way to properly escape such characters when there are odd numbers of quotation marks in a line. Otherwise it's easy but messy. -
Rich almost 14 yearsOh, just another thing:
for
skips empty lines. If you need the file to survive including those you have to look for other solutions.