7

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.

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
)
  • Part 2 has the fix. Thanks for the contribution! – Carla Hook Dec 2 '13 at 17:32
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

  • 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 Dec 2 '13 at 17:23
  • @CarlaHook You can easily disable this with another parameter when running a PowerShell script, see stackoverflow.com/a/9167524/5008962. – rugk Feb 8 '19 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.