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

6

1

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.

Carla Hook

Posted 2013-11-11T12:37:33.847

Reputation: 455

Answers

6

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
)

Scott McKinney

Posted 2013-11-11T12:37:33.847

Reputation: 884

Part 2 has the fix. Thanks for the contribution! – Carla Hook – 2013-12-02T17:32:07.217

8

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

thisguy123

Posted 2013-11-11T12:37:33.847

Reputation: 236

@CarlaHook You can easily disable this with another parameter when running a PowerShell script, see https://stackoverflow.com/a/9167524/5008962.

– rugk – 2019-02-08T09:31:08.323

I tested this using my PC at home and it works. Sadly, my workplace PC have PowerShell scripting disabled, leaving me with the default Windows CMD prompt. Thanks anyway :) – Carla Hook – 2013-12-02T17:23:27.510