Search code examples
stringbatch-filerenamewords

run a script to rename several words in a txt file


I need your help. I have a txt file in a directory (folder) and need to run a script to rename several words, eg.

where LX4XAB to LX4xab and where is XS3X44 to Xs3x44 and another word

until the end save the file with another name.

Can you help me? Thank you.


Solution

  • Here you go:

    @echo off
    setlocal enabledelayedexpansion
    (for /f "tokens=*" %%f in (input1.txt) do (
            set "line=%%f"
            set "line=!line:LX4XAB=LX4xab!"
            set "line=!line:XS3X44=Xs3x44!"
            echo(!line!
    )) > newfile.txt
    

    Revision 1

    Here is how you can do it with multiple files and doing the naming the way you asked for.

    @echo off
    setlocal enabledelayedexpansion
    cd /d C:\Temp
    for %%a in (*.txt) do (
      echo %%~nxa|Find /i "_new">nul
      if errorlevel 1 (
        (for /f "tokens=*" %%f in (%%a) do (
            set "line=%%f"
            set "line=!line:LX4XAB=LX4xab!"
            set "line=!line:XS3X44=Xs3x44!"
            echo(!line!
        )) > %%~na_new.txt
      ) 
      echo %%~nxa|Find /i "_new">nul
      if errorlevel 1 ren %%~nxa %%~na.old
    )