Wednesday, 4 September 2019

command line - How to search and replace a string in multiple text files (within a directory) with Windows CMD?


I have multiple text files within a directory, each of which I want to replace every occurrence of the string 1 setlinewidth to 10 setlinewidth. How do I do this via Windows cmd? Please help.



Answer



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
)

No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...