Windows IT Pro

Fix it yourself!

How to edit files using batch script?

Ever wondered how to edit multiple files with a single script? Well I did,  and I am sure everyone who is reading this post must have. :) Imagine there are hundreds of files (for e.g., signatures of all the employees) and you were asked to edit (eg., name of the company) all the signatures. It takes a great amount of time if we manually edit them individually. Well, the answer for our problem is a single batch script that can take care of our problem with just one click. Here’s an example:

1.Open Notepad,  Copy and paste the below script :

@echo off
REM — Prepare the Command Processor –
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

::BatchSubstitude – parses a File line by line and replaces a substring”
::syntax: BatchSubstitude.bat OldStr NewStr File
::          OldStr [in] – string to be replaced
::          NewStr [in] – string to replace with
::          File   [in] – file to be parsed
if “%*”==”” findstr “^::” “%~f0″&GOTO:EOF
for /f “tokens=1,* delims=]” %%A in (‘”type %3|find /n /v “””‘) do (
    set “line=%%B”
    if defined line (
        call set “line=echo.%%line:%~1=%~2%%”
        for /f “delims=” %%X in (‘”echo.”%%line%%””‘) do %%~X
    ) ELSE echo.
)

2. Save the file as “xyz.bat”

The above script will parses a file line by line and will replaces a desired substring.

3. Open cmd prompt >> type the following command:

c:\xyz.bat “text-to-replace” text-to-replace-with c:\FileToEdit.txt > c:\Edited_file.txt

ScriptCmd

 xyz.bat is the batch script we have created in Step 1; FileToEdit.txt is the file you would like to edit; and Edited_File.txt is an edited file.

The command will edit the file (FileToEdit.txt) and output into a new file (Edited_File.txt).

File to edit

File to edit

Output - Edited file

Output - Edited file

  This script can also edit an htlml file. I haven’t tried the script on other file formats (e.g., .aspx, .rtf, etc…). If anyone did, then please let me know if it works.

The only drawback of this script is, it cannot recognize the spaces in a string. I wasn’t able to figure out how to edit a complete sentence. Instead I used a lengthy but effective way to edit 2 or more strings in a file. Try the following script:

c:\xyz.bat “First-string-to-replace” string-to-replace-with c:\FileToEdit.txt > c:\Edited_temp.txt

“The above command will replace the first substring and output into ‘Edited_temp.txt’ file.”

c:\xyz.bat “Second-string-to-replace” string-to-replace-with c:\Edited_temp.txt > c:\Edited_final_file.txt

 “The above command will replace the second substring from ‘Edited_temp.txt’ file and output into a new file i.e., ‘Edited_final_file.txt’ “

del c:\Edited_temp.txt

“It will delete the ‘Edited_temp.txt’ file”

Do let me know, if anyone figured out how to replace a complete sentence using a single command line.

You can furhter manipulate the script accordingly to add any conditional statements etc… Hope this article helps. :)

Tip of the day: Test all your batch scripts in a Virtual machine. To know how to create a virtual machine, please visit http://technet.microsoft.com/en-us/library/cc708299(WS.10).aspx 

Rule of the day: Do you understand the value of consistency?

Author: Syed Dilawer Mehdi - Software Developer/Network Administrator

About these ads

July 31, 2009 - Posted by | Batch Script

6 Comments »

  1. Thanks for this tutorial.
    I stumbled upon this via Google Search…
    “edit part of a line in text file with batch”.

    Unfortunately I’m not DOS savvy but I know what I’m trying to do :-)
    Using Batch, I’m trying to edit an MP3 master playlist (text) file (.m3u),
    to remove the absolute path on each line and only leave the relative path of parent folder and file name.

    FOR EXAMPLE:

    C:\My Music\parent folder1 – parent folder.mp3
    C:\My Music\parent folder\child folder 11 – child folder 1.mp3
    C:\My Music\parent folder\child folder 21 – child folder 2.mp3

    IS TRANSFORMED TO THIS (in the text file):

    parent folder1 – parent folder.mp3
    parent folder\child folder 11 – child folder 1.mp3
    parent folder\child folder 21 – child folder 2.mp3

    —————————————————-

    As a matter of interest to you…

    This code creates “playlist.m3u” for [*.mp3] in all subdirs and places it in each subdir:

    for /R %%A in (*.mp3) do @echo %%~nxA >> “%%~dpAplaylist.m3u”

    Not what I want.
    Yes, it outputs in bare (file name only) format but
    I’m after a master playlist from Parent Directory,
    Not separate playlists in each subdirectory.

    The following code creates a master playlist file in parent directory AND auto-renames the file to “parent folder.m3u”.

    CD %1
    Dir /o:n /s /b *.flac *.mp3 *.ogg *.ape *.m4a >TempPlaylist.m3u
    Set foldervar=%CD%
    Set foldervar=%foldervar:*\=%
    Set foldervar=%foldervar:*\=%
    Set foldervar=%foldervar:*\=%
    Set foldervar=%foldervar:*\=%
    Set foldervar=%foldervar:*\=%
    Ren TempPlaylist.m3u “%foldervar%.m3u”

    NICE…
    Unfortunately it still leaves me with absolute path names which, as you know, I don’t want.
    So I need to edit the lines to have ‘parent folder’ as root….ie. Relative Paths.

    Thanks again for your article,
    and I hope what I wrote was understandable…
    Cheers

    Comment by Nick | August 25, 2009 | Reply

  2. Hi Nick,

    Correct me if I am wrong, you want to edit the absolute path in each line of a text file?
    If yes, then you can try the same method and batch file as discussed in the tutorial.

    Try this:
    1. Follow step 1 of this tutorial to create a batch file.
    2. Open cmd prompt and type the following command:

    (path of the batch file) “C:\My” “” (path of your text file) > C:\temp.txt

    For example: C:\Users\Nick\Documents\FindAndReplace.bat “C:\My” “” C:\Users\Nick\Music\Playlist\MyPlaylist.txt > C:\temp.txt

    then

    Type the same command to remove Music from temp.txt file.

    For example: C:\Users\Nick\Documents\FindAndReplace.bat “Music\” “” C:\Temp.txt > C:\playlist.txt

    This will leave your playlist.txt file with relative path..
    For example:
    parent folder1 – parent folder.mp3

    I hope made some sense here… and moreover this is what you were looking for.. :)

    All the best .. :)

    Comment by Syed Mehdi | August 27, 2009 | Reply

  3. To include spaces change the script from: if “%*” to if “%skip%*”

    Then try like this:

    c:\xyz.bat “First-string-to-replace” “string-to-replace-with” c:\FileToEdit.txt > c:\Edited_temp.txt

    Works a treat thanks for the original script!

    Comment by Richard Fall | September 10, 2009 | Reply

  4. My requirement is different:
    I need to load data in dataase with using sql Script. I have a more than 20 sql script in different sub folder. Run time I want to change Schema name in SQL file. Please Let me know How I can do with using DOS command

    Comment by Hirdesh | March 6, 2010 | Reply

  5. My brother recommended I might like this web site. He
    was entirely right. This post truly made my day.
    You cann’t imagine simply how much time I had spent for this information! Thanks!

    Comment by cold call | March 12, 2013 | Reply

  6. This website was… how do I say it? Relevant!
    ! Finally I have found something which helped me.
    Thanks!

    Comment by evenflo car seat | March 25, 2013 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: