0

I have over one hundred txt files, and in each file are words which need to be changed.

If anyone can help me fix this I would appreciate it.

Here is my script:

@echo off

set "Find=Earth"
set "Replace=World"

set "source=Folder1"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%source%\*.txt"') do (
      set "line=%%b"
      if defined line set "line=!line:%Find%=%Replace%!"
      echo(!line!
   )
) > %source%\%%~nxa.txt.bak

I was trying with a test file to find the word Earth and replace it with another word, or delete it completely.

document 1.txt

Earth

%~nxa.txt.bak

1. World

Somehow, I get a number and the output I get %~nxa.txt.bak

I did take a look around the site, and I did find a script that changes data, but it took too long to do so.

  • `if defined line set "line=!line:%Find%=%Replaced%!"` Um- you're establishing `replace`, `not `replaceD` and your ouput file is source%\%%~nx**a**.txt.bak where `%%a` is the line number, but actually - your code is the wrong approach... – Magoo Feb 28 '23 at 23:51
  • Oh Ok, I corrected the D so what would be the right approach, I did find a script that uses TYPE but man it took forever, it was way to slow for editing I'm looking for simple with batch scripting – James Thomas Feb 28 '23 at 23:56

1 Answers1

0
for %%e in ("%source%\*.txt") do (
 for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%%e"') do (
  set "line=%%b"
  if defined line set "line=!line:%Find%=%Replace%!"
  echo(!line!
 )
) > %source%\%%~nxe.txt.bak

should cure your problem - %%e contains the filename, %%a the line number within the file %%e and %%b the line contents.

Magoo
  • 77,302
  • 8
  • 62
  • 84