How to search and replace a string in multiple text files (within a directory) with Windows CMD?
Powershell has utilities that will solve this problem without downloading any external software or utilities. Check out this article by the Scripting Guy, it's pretty good. Also I'd say take a look at the Set-Content documentation.
Example:
(Get-Content C:\Scripts\Test.txt) |
Foreach-Object {$_ -replace "oldString", "newString"} |
Set-Content C:\Scripts\Test.txt
If you can install third-party utilities, Gnu sed is tailor-made for this type of operation. The link points to a Windows version hosted at Sourceforge that you can download and install. This would be the syntax at the prompt:
for %i in (*.txt) do sed -i "s/1 setlinewidth/10 setlinewidth/g" %i
Note: with the -i
option, sed is going to overwrite the files in question, so make sure you have easily available backups just in case something goes wrong.
If you can't install the sed utility, this is going to be much more difficult using just the built-in batch language.
Edit: I put together a small batch file that will perform the replacement without any external tools. Save it as foo.cmd
or whatever your preferred name is and invoke it from the command line as: foo.cmd
A caveat: This is written very specifically from the examples in your question. If there is other text or even extra spaces at the beginning or end of the line before/after 1 setlinewidth
, this batch file will not work. This will also save a copy of the original text file as with a .bak extension (e.g. textfile.txt.bak).
@echo off
setlocal ENABLEEXTENSIONS
setlocal ENABLEDELAYEDEXPANSION
for %%a in (*.txt) do (
echo Processing %%a...
for /f "delims=^ tokens=1" %%i in (%%a) do (
if /i "%%i"=="1 setlinewidth" (
echo 10 setlinewidth>>%%a.new
) else (
echo %%i>>%%a.new
)
)
move /y %%a %%a.bak > nul
ren %%a.new %%a
)