Looking to create a batch file capable of editing a line (or word) in a text file











up vote
3
down vote

favorite
2












I have a text file (...config.txt) containing 2 lines which looks like:



Preamp: -4 dB
Include: surround.txt


I need to change "surround" to "headphones" in that config file. I really need to make 2 batch files. One for "headphones" and one for "surround".



The config file in question is a file related to EqualizerAPO that calls a separate file containing EQ settings for a particular listening environment. In the example above, "surround". However, there can be many others. That config file, when saved, automatically triggers the EQ settings it's calling under the "include" line. The reason I need this is because, if I need to change the listening environment to something else, I need to browse to the directory, open the config.txt file, edit the "Include"
section to my needs, then save. It becomes tedious when I have to change it when the need arises. I really need a one-click solution. Any help would be greatly appreciated. Thank you!



EDIT:



The directory (containing that "config.txt" file referred to earlier):



C:Program FilesEqualizerAPOconfig


contains 2 types of text files: EQ settings files (e.g. headphones, surround, theater, etc. Basically the files that users create and export in TXT format via software called Room EQ Wizard. We'll call them "reference" files.) The other is the actual single config file that EqualizerAPO uses to determine which "reference" file it needs to use and adjust it's EQ settings accordingly. EqualizerAPO attaches itself to the system effect infrastructure as an Audio Processing Object. All I need is a simple solution that would allow me to change the line "Include: surround.txt" to whatever other EQ file I need to use at that time. I am constantly switching between EQs, hence my coming here. If possible, I'd like to be presented with a list of choices.



For example:



Select from the following equalizers:

1. Headphones
2. Surround
3. Theater
4. ***
5. ***

Enter the number:_


And then exit when the number is chosen.



Ideally, it'd be nice to have a very minimal application of some sort running in the taskbar that allows a one-click solution, removing the use of batch files entirely. However, that is not a necessity. Batch files are fine for the time being.










share|improve this question
























  • I really need to make 2 batch files. One for "headphones" and one for "surround" What do you mean ? A batch file to change surround to headphones and another batch file to change headphones to surround ? And finally, is batch mandatory or Powershell is an available option ?
    – user2196728
    Jan 12 '14 at 1:49








  • 4




    Why not just make 2 copies of the file config.txt and config-2.txt and just rename them as needed?
    – cybernard
    Jan 12 '14 at 1:53










  • +1 to cybernard ! This way your batch files will just use rename :) easy !
    – user2196728
    Jan 12 '14 at 2:02












  • @user2196728 I've edited the OP for clarification. "A batch file to change surround to headphones and another batch file to change headphones to surround?" That's correct. Regarding Powershell, I've only used it once or twice before, but I don't see an issue with
    – Steve
    Jan 12 '14 at 4:27












  • Regarding cybernard suggestion - it requires at least 2 RENAMEs per change. I suggest using a single COPY instead. So you could have headphones.txt and surround.txt, and simply copy either one to config.txt as needed.
    – dbenham
    Jan 12 '14 at 15:26















up vote
3
down vote

favorite
2












I have a text file (...config.txt) containing 2 lines which looks like:



Preamp: -4 dB
Include: surround.txt


I need to change "surround" to "headphones" in that config file. I really need to make 2 batch files. One for "headphones" and one for "surround".



The config file in question is a file related to EqualizerAPO that calls a separate file containing EQ settings for a particular listening environment. In the example above, "surround". However, there can be many others. That config file, when saved, automatically triggers the EQ settings it's calling under the "include" line. The reason I need this is because, if I need to change the listening environment to something else, I need to browse to the directory, open the config.txt file, edit the "Include"
section to my needs, then save. It becomes tedious when I have to change it when the need arises. I really need a one-click solution. Any help would be greatly appreciated. Thank you!



EDIT:



The directory (containing that "config.txt" file referred to earlier):



C:Program FilesEqualizerAPOconfig


contains 2 types of text files: EQ settings files (e.g. headphones, surround, theater, etc. Basically the files that users create and export in TXT format via software called Room EQ Wizard. We'll call them "reference" files.) The other is the actual single config file that EqualizerAPO uses to determine which "reference" file it needs to use and adjust it's EQ settings accordingly. EqualizerAPO attaches itself to the system effect infrastructure as an Audio Processing Object. All I need is a simple solution that would allow me to change the line "Include: surround.txt" to whatever other EQ file I need to use at that time. I am constantly switching between EQs, hence my coming here. If possible, I'd like to be presented with a list of choices.



For example:



Select from the following equalizers:

1. Headphones
2. Surround
3. Theater
4. ***
5. ***

Enter the number:_


And then exit when the number is chosen.



Ideally, it'd be nice to have a very minimal application of some sort running in the taskbar that allows a one-click solution, removing the use of batch files entirely. However, that is not a necessity. Batch files are fine for the time being.










share|improve this question
























  • I really need to make 2 batch files. One for "headphones" and one for "surround" What do you mean ? A batch file to change surround to headphones and another batch file to change headphones to surround ? And finally, is batch mandatory or Powershell is an available option ?
    – user2196728
    Jan 12 '14 at 1:49








  • 4




    Why not just make 2 copies of the file config.txt and config-2.txt and just rename them as needed?
    – cybernard
    Jan 12 '14 at 1:53










  • +1 to cybernard ! This way your batch files will just use rename :) easy !
    – user2196728
    Jan 12 '14 at 2:02












  • @user2196728 I've edited the OP for clarification. "A batch file to change surround to headphones and another batch file to change headphones to surround?" That's correct. Regarding Powershell, I've only used it once or twice before, but I don't see an issue with
    – Steve
    Jan 12 '14 at 4:27












  • Regarding cybernard suggestion - it requires at least 2 RENAMEs per change. I suggest using a single COPY instead. So you could have headphones.txt and surround.txt, and simply copy either one to config.txt as needed.
    – dbenham
    Jan 12 '14 at 15:26













up vote
3
down vote

favorite
2









up vote
3
down vote

favorite
2






2





I have a text file (...config.txt) containing 2 lines which looks like:



Preamp: -4 dB
Include: surround.txt


I need to change "surround" to "headphones" in that config file. I really need to make 2 batch files. One for "headphones" and one for "surround".



The config file in question is a file related to EqualizerAPO that calls a separate file containing EQ settings for a particular listening environment. In the example above, "surround". However, there can be many others. That config file, when saved, automatically triggers the EQ settings it's calling under the "include" line. The reason I need this is because, if I need to change the listening environment to something else, I need to browse to the directory, open the config.txt file, edit the "Include"
section to my needs, then save. It becomes tedious when I have to change it when the need arises. I really need a one-click solution. Any help would be greatly appreciated. Thank you!



EDIT:



The directory (containing that "config.txt" file referred to earlier):



C:Program FilesEqualizerAPOconfig


contains 2 types of text files: EQ settings files (e.g. headphones, surround, theater, etc. Basically the files that users create and export in TXT format via software called Room EQ Wizard. We'll call them "reference" files.) The other is the actual single config file that EqualizerAPO uses to determine which "reference" file it needs to use and adjust it's EQ settings accordingly. EqualizerAPO attaches itself to the system effect infrastructure as an Audio Processing Object. All I need is a simple solution that would allow me to change the line "Include: surround.txt" to whatever other EQ file I need to use at that time. I am constantly switching between EQs, hence my coming here. If possible, I'd like to be presented with a list of choices.



For example:



Select from the following equalizers:

1. Headphones
2. Surround
3. Theater
4. ***
5. ***

Enter the number:_


And then exit when the number is chosen.



Ideally, it'd be nice to have a very minimal application of some sort running in the taskbar that allows a one-click solution, removing the use of batch files entirely. However, that is not a necessity. Batch files are fine for the time being.










share|improve this question















I have a text file (...config.txt) containing 2 lines which looks like:



Preamp: -4 dB
Include: surround.txt


I need to change "surround" to "headphones" in that config file. I really need to make 2 batch files. One for "headphones" and one for "surround".



The config file in question is a file related to EqualizerAPO that calls a separate file containing EQ settings for a particular listening environment. In the example above, "surround". However, there can be many others. That config file, when saved, automatically triggers the EQ settings it's calling under the "include" line. The reason I need this is because, if I need to change the listening environment to something else, I need to browse to the directory, open the config.txt file, edit the "Include"
section to my needs, then save. It becomes tedious when I have to change it when the need arises. I really need a one-click solution. Any help would be greatly appreciated. Thank you!



EDIT:



The directory (containing that "config.txt" file referred to earlier):



C:Program FilesEqualizerAPOconfig


contains 2 types of text files: EQ settings files (e.g. headphones, surround, theater, etc. Basically the files that users create and export in TXT format via software called Room EQ Wizard. We'll call them "reference" files.) The other is the actual single config file that EqualizerAPO uses to determine which "reference" file it needs to use and adjust it's EQ settings accordingly. EqualizerAPO attaches itself to the system effect infrastructure as an Audio Processing Object. All I need is a simple solution that would allow me to change the line "Include: surround.txt" to whatever other EQ file I need to use at that time. I am constantly switching between EQs, hence my coming here. If possible, I'd like to be presented with a list of choices.



For example:



Select from the following equalizers:

1. Headphones
2. Surround
3. Theater
4. ***
5. ***

Enter the number:_


And then exit when the number is chosen.



Ideally, it'd be nice to have a very minimal application of some sort running in the taskbar that allows a one-click solution, removing the use of batch files entirely. However, that is not a necessity. Batch files are fine for the time being.







command-line batch-file text-editing editing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 9 '15 at 11:32









Hennes

58.7k792141




58.7k792141










asked Jan 12 '14 at 1:43









Steve

16113




16113












  • I really need to make 2 batch files. One for "headphones" and one for "surround" What do you mean ? A batch file to change surround to headphones and another batch file to change headphones to surround ? And finally, is batch mandatory or Powershell is an available option ?
    – user2196728
    Jan 12 '14 at 1:49








  • 4




    Why not just make 2 copies of the file config.txt and config-2.txt and just rename them as needed?
    – cybernard
    Jan 12 '14 at 1:53










  • +1 to cybernard ! This way your batch files will just use rename :) easy !
    – user2196728
    Jan 12 '14 at 2:02












  • @user2196728 I've edited the OP for clarification. "A batch file to change surround to headphones and another batch file to change headphones to surround?" That's correct. Regarding Powershell, I've only used it once or twice before, but I don't see an issue with
    – Steve
    Jan 12 '14 at 4:27












  • Regarding cybernard suggestion - it requires at least 2 RENAMEs per change. I suggest using a single COPY instead. So you could have headphones.txt and surround.txt, and simply copy either one to config.txt as needed.
    – dbenham
    Jan 12 '14 at 15:26


















  • I really need to make 2 batch files. One for "headphones" and one for "surround" What do you mean ? A batch file to change surround to headphones and another batch file to change headphones to surround ? And finally, is batch mandatory or Powershell is an available option ?
    – user2196728
    Jan 12 '14 at 1:49








  • 4




    Why not just make 2 copies of the file config.txt and config-2.txt and just rename them as needed?
    – cybernard
    Jan 12 '14 at 1:53










  • +1 to cybernard ! This way your batch files will just use rename :) easy !
    – user2196728
    Jan 12 '14 at 2:02












  • @user2196728 I've edited the OP for clarification. "A batch file to change surround to headphones and another batch file to change headphones to surround?" That's correct. Regarding Powershell, I've only used it once or twice before, but I don't see an issue with
    – Steve
    Jan 12 '14 at 4:27












  • Regarding cybernard suggestion - it requires at least 2 RENAMEs per change. I suggest using a single COPY instead. So you could have headphones.txt and surround.txt, and simply copy either one to config.txt as needed.
    – dbenham
    Jan 12 '14 at 15:26
















I really need to make 2 batch files. One for "headphones" and one for "surround" What do you mean ? A batch file to change surround to headphones and another batch file to change headphones to surround ? And finally, is batch mandatory or Powershell is an available option ?
– user2196728
Jan 12 '14 at 1:49






I really need to make 2 batch files. One for "headphones" and one for "surround" What do you mean ? A batch file to change surround to headphones and another batch file to change headphones to surround ? And finally, is batch mandatory or Powershell is an available option ?
– user2196728
Jan 12 '14 at 1:49






4




4




Why not just make 2 copies of the file config.txt and config-2.txt and just rename them as needed?
– cybernard
Jan 12 '14 at 1:53




Why not just make 2 copies of the file config.txt and config-2.txt and just rename them as needed?
– cybernard
Jan 12 '14 at 1:53












+1 to cybernard ! This way your batch files will just use rename :) easy !
– user2196728
Jan 12 '14 at 2:02






+1 to cybernard ! This way your batch files will just use rename :) easy !
– user2196728
Jan 12 '14 at 2:02














@user2196728 I've edited the OP for clarification. "A batch file to change surround to headphones and another batch file to change headphones to surround?" That's correct. Regarding Powershell, I've only used it once or twice before, but I don't see an issue with
– Steve
Jan 12 '14 at 4:27






@user2196728 I've edited the OP for clarification. "A batch file to change surround to headphones and another batch file to change headphones to surround?" That's correct. Regarding Powershell, I've only used it once or twice before, but I don't see an issue with
– Steve
Jan 12 '14 at 4:27














Regarding cybernard suggestion - it requires at least 2 RENAMEs per change. I suggest using a single COPY instead. So you could have headphones.txt and surround.txt, and simply copy either one to config.txt as needed.
– dbenham
Jan 12 '14 at 15:26




Regarding cybernard suggestion - it requires at least 2 RENAMEs per change. I suggest using a single COPY instead. So you could have headphones.txt and surround.txt, and simply copy either one to config.txt as needed.
– dbenham
Jan 12 '14 at 15:26










2 Answers
2






active

oldest

votes

















up vote
1
down vote













See if this helps. I had this from when I needed to perform a search and replace on an XML file. The strings, as long as you enclose them in double-quotes, can have special characters such as greater than and less than (used as redirection by scripts, ignored here). If you don't like the usage of variables to define the files you want to modify, you could make them into arguments which you could pass to the script. But then you would have to change the logic to shift the parameters unless you explicitly say "parameter 1 is the file to be changed, parameter 2 is the string to be found, etc..."



Hope this helps someone. Windows XP or higher is required.



::Find and Replace script allows the user to 
::define a file path, file name and a string
::to find and replace so as to create a new file.
::
::Original file is backed up with an added extension of *.bak, in case
::the user finds the need to go back to the original.

@echo off
::Use the path from whence the script was executed as
::the Current Working Directory
set CWD=%~dp0

::***BEGIN MODIFY BLOCK***
::The variables below should be modified to the
::files to be changed and the strings to find/replace
::Include trailing backslash in _FilePath
set _FilePath=PathToFile
set _FileName=FileNameToModify
::_WrkFile is the file on which the script will make
::modifications.
set _WrkFile=BackupFileName
set OldStr="The string to be found and replaced, enclosed in double-quotes"
set NewStr="The new string to replace the value of OldStr, enclosed in double-quotes"
::***END MODIFY BLOCK***

::Set a variable which is used by the
::search and replace section to let us
::know if the string to be modified was
::found or not.
set _Found=Not found

SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION

if not exist "%_FilePath%%_FileName%" goto :NotFound

::If a backup file exists, delete it
if exist "%_FilePath%%_WrkFile%" (
echo Deleting "%_FilePath%%_WrkFile%"
del "%_FilePath%%_WrkFile%" >nul 2>&1
)

echo.
echo Backing up "%_FilePath%%_FileName%"...
copy "%_FilePath%%_FileName%" "%_FilePath%%_WrkFile%" /v

::Delete the original file. No worries, we got a backup.
if exist "%_FilePath%%_FileName%" del "%_FilePath%%_FileName%"
echo.
echo Searching for %OldStr% string...
echo.
for /f "usebackq tokens=*" %%a in ("%_FilePath%%_WrkFile%") do (
set _LineChk=%%a
if "!_LineChk!"==%OldStr% (
SET _Found=Found
SET NewStr=!NewStr:^"=!
echo !NewStr!
) else (echo %%a)
)>>"%_FilePath%%_FileName%" 2>&1

::If we didn't find the string, rename the backup file to the original file name
::Otherwise, delete the _WorkFile as we re-created the original file when the
::string was found and replaced.
if /i "!_Found!"=="Not found" (echo !_Found! && del "%_FilePath%%_FileName%" && ren "%_FilePath%%_WrkFile%" %_FileName%) else (echo !_Found! && del "%_FilePath%%_WrkFile%")
goto :exit

:NotFound
echo.
echo File "%_FilePath%%_FileName%" missing.
echo Cannot continue...
echo.
:: Pause script for approx. 10 seconds...
PING 127.0.0.1 -n 11 > NUL 2>&1
goto :Exit

:Exit
exit /b





share|improve this answer






























    up vote
    0
    down vote













    This should do the trick:



    $filepath = "C:Program FilesEqualizerAPOconfigconfig.txt";
    $equalizer = "";
    $equalizers = @("Headphones","Surround","Theater"); # Add all options here.

    if( -not (test-path $filepath))
    {
    Write-Host "File: `"$filepath`" not found";
    exit(1);
    }


    if($args.count -gt 0)
    {
    if($args[0] -ge 0 -and $args[0] -lt $equalizers.length)
    {
    $equalizer = $equalizers[[int]$args[0]];
    }
    elseif($equalizers -contains $args[0])
    {
    $equalizer = $args[0];
    }
    else
    {
    Write-Host "Invalid argument";
    exit(1);
    }
    }
    else
    {
    Write-Host "Select from the following equalizers:";

    $i=0;

    foreach( $option in $equalizers)
    {
    Write-Host "$i. $option";
    $i++;
    }
    $choice = Read-Host "Enter choice:";

    if($choice -ge 0 -and $choice -lt $equalizers.length)
    {
    $equalizer = $equalizers[[int]$choice];
    }
    else
    {
    Write-Host "Invalid choice";
    exit(1);
    }
    }

    Write-Host "Changing config file to use $equalizer";

    (Get-Content $filepath) | %{

    $_ -replace '^Include: .*$', ("Include: $equalizer.txt")

    } | Set-Content $filepath

    exit(0);


    Save as filename.ps1 and create a bat file named filename.cmd and place them both somewhere in your PATH, that way you can run the script by typing "filename" in either windows start menu or run.



    paste the following in the bat file:



    @echo off
    if [%1]== goto none
    powershell "& '%~dp0filename.ps1' '%1'"
    goto end
    :none
    powershell "& '%~dp0filename.ps1'"
    :end


    PS: if you havent before be sure to enable running of powershell scripts:



    powershell "set-executionpolicy remotesigned"





    share|improve this answer





















    • You should state at the beginning of your question that the code that follows is not a batch file. apart from 7 lines at the end
      – barlop
      Nov 5 '15 at 12:59













    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "3"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f700458%2flooking-to-create-a-batch-file-capable-of-editing-a-line-or-word-in-a-text-fil%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    See if this helps. I had this from when I needed to perform a search and replace on an XML file. The strings, as long as you enclose them in double-quotes, can have special characters such as greater than and less than (used as redirection by scripts, ignored here). If you don't like the usage of variables to define the files you want to modify, you could make them into arguments which you could pass to the script. But then you would have to change the logic to shift the parameters unless you explicitly say "parameter 1 is the file to be changed, parameter 2 is the string to be found, etc..."



    Hope this helps someone. Windows XP or higher is required.



    ::Find and Replace script allows the user to 
    ::define a file path, file name and a string
    ::to find and replace so as to create a new file.
    ::
    ::Original file is backed up with an added extension of *.bak, in case
    ::the user finds the need to go back to the original.

    @echo off
    ::Use the path from whence the script was executed as
    ::the Current Working Directory
    set CWD=%~dp0

    ::***BEGIN MODIFY BLOCK***
    ::The variables below should be modified to the
    ::files to be changed and the strings to find/replace
    ::Include trailing backslash in _FilePath
    set _FilePath=PathToFile
    set _FileName=FileNameToModify
    ::_WrkFile is the file on which the script will make
    ::modifications.
    set _WrkFile=BackupFileName
    set OldStr="The string to be found and replaced, enclosed in double-quotes"
    set NewStr="The new string to replace the value of OldStr, enclosed in double-quotes"
    ::***END MODIFY BLOCK***

    ::Set a variable which is used by the
    ::search and replace section to let us
    ::know if the string to be modified was
    ::found or not.
    set _Found=Not found

    SETLOCAL
    SETLOCAL ENABLEDELAYEDEXPANSION

    if not exist "%_FilePath%%_FileName%" goto :NotFound

    ::If a backup file exists, delete it
    if exist "%_FilePath%%_WrkFile%" (
    echo Deleting "%_FilePath%%_WrkFile%"
    del "%_FilePath%%_WrkFile%" >nul 2>&1
    )

    echo.
    echo Backing up "%_FilePath%%_FileName%"...
    copy "%_FilePath%%_FileName%" "%_FilePath%%_WrkFile%" /v

    ::Delete the original file. No worries, we got a backup.
    if exist "%_FilePath%%_FileName%" del "%_FilePath%%_FileName%"
    echo.
    echo Searching for %OldStr% string...
    echo.
    for /f "usebackq tokens=*" %%a in ("%_FilePath%%_WrkFile%") do (
    set _LineChk=%%a
    if "!_LineChk!"==%OldStr% (
    SET _Found=Found
    SET NewStr=!NewStr:^"=!
    echo !NewStr!
    ) else (echo %%a)
    )>>"%_FilePath%%_FileName%" 2>&1

    ::If we didn't find the string, rename the backup file to the original file name
    ::Otherwise, delete the _WorkFile as we re-created the original file when the
    ::string was found and replaced.
    if /i "!_Found!"=="Not found" (echo !_Found! && del "%_FilePath%%_FileName%" && ren "%_FilePath%%_WrkFile%" %_FileName%) else (echo !_Found! && del "%_FilePath%%_WrkFile%")
    goto :exit

    :NotFound
    echo.
    echo File "%_FilePath%%_FileName%" missing.
    echo Cannot continue...
    echo.
    :: Pause script for approx. 10 seconds...
    PING 127.0.0.1 -n 11 > NUL 2>&1
    goto :Exit

    :Exit
    exit /b





    share|improve this answer



























      up vote
      1
      down vote













      See if this helps. I had this from when I needed to perform a search and replace on an XML file. The strings, as long as you enclose them in double-quotes, can have special characters such as greater than and less than (used as redirection by scripts, ignored here). If you don't like the usage of variables to define the files you want to modify, you could make them into arguments which you could pass to the script. But then you would have to change the logic to shift the parameters unless you explicitly say "parameter 1 is the file to be changed, parameter 2 is the string to be found, etc..."



      Hope this helps someone. Windows XP or higher is required.



      ::Find and Replace script allows the user to 
      ::define a file path, file name and a string
      ::to find and replace so as to create a new file.
      ::
      ::Original file is backed up with an added extension of *.bak, in case
      ::the user finds the need to go back to the original.

      @echo off
      ::Use the path from whence the script was executed as
      ::the Current Working Directory
      set CWD=%~dp0

      ::***BEGIN MODIFY BLOCK***
      ::The variables below should be modified to the
      ::files to be changed and the strings to find/replace
      ::Include trailing backslash in _FilePath
      set _FilePath=PathToFile
      set _FileName=FileNameToModify
      ::_WrkFile is the file on which the script will make
      ::modifications.
      set _WrkFile=BackupFileName
      set OldStr="The string to be found and replaced, enclosed in double-quotes"
      set NewStr="The new string to replace the value of OldStr, enclosed in double-quotes"
      ::***END MODIFY BLOCK***

      ::Set a variable which is used by the
      ::search and replace section to let us
      ::know if the string to be modified was
      ::found or not.
      set _Found=Not found

      SETLOCAL
      SETLOCAL ENABLEDELAYEDEXPANSION

      if not exist "%_FilePath%%_FileName%" goto :NotFound

      ::If a backup file exists, delete it
      if exist "%_FilePath%%_WrkFile%" (
      echo Deleting "%_FilePath%%_WrkFile%"
      del "%_FilePath%%_WrkFile%" >nul 2>&1
      )

      echo.
      echo Backing up "%_FilePath%%_FileName%"...
      copy "%_FilePath%%_FileName%" "%_FilePath%%_WrkFile%" /v

      ::Delete the original file. No worries, we got a backup.
      if exist "%_FilePath%%_FileName%" del "%_FilePath%%_FileName%"
      echo.
      echo Searching for %OldStr% string...
      echo.
      for /f "usebackq tokens=*" %%a in ("%_FilePath%%_WrkFile%") do (
      set _LineChk=%%a
      if "!_LineChk!"==%OldStr% (
      SET _Found=Found
      SET NewStr=!NewStr:^"=!
      echo !NewStr!
      ) else (echo %%a)
      )>>"%_FilePath%%_FileName%" 2>&1

      ::If we didn't find the string, rename the backup file to the original file name
      ::Otherwise, delete the _WorkFile as we re-created the original file when the
      ::string was found and replaced.
      if /i "!_Found!"=="Not found" (echo !_Found! && del "%_FilePath%%_FileName%" && ren "%_FilePath%%_WrkFile%" %_FileName%) else (echo !_Found! && del "%_FilePath%%_WrkFile%")
      goto :exit

      :NotFound
      echo.
      echo File "%_FilePath%%_FileName%" missing.
      echo Cannot continue...
      echo.
      :: Pause script for approx. 10 seconds...
      PING 127.0.0.1 -n 11 > NUL 2>&1
      goto :Exit

      :Exit
      exit /b





      share|improve this answer

























        up vote
        1
        down vote










        up vote
        1
        down vote









        See if this helps. I had this from when I needed to perform a search and replace on an XML file. The strings, as long as you enclose them in double-quotes, can have special characters such as greater than and less than (used as redirection by scripts, ignored here). If you don't like the usage of variables to define the files you want to modify, you could make them into arguments which you could pass to the script. But then you would have to change the logic to shift the parameters unless you explicitly say "parameter 1 is the file to be changed, parameter 2 is the string to be found, etc..."



        Hope this helps someone. Windows XP or higher is required.



        ::Find and Replace script allows the user to 
        ::define a file path, file name and a string
        ::to find and replace so as to create a new file.
        ::
        ::Original file is backed up with an added extension of *.bak, in case
        ::the user finds the need to go back to the original.

        @echo off
        ::Use the path from whence the script was executed as
        ::the Current Working Directory
        set CWD=%~dp0

        ::***BEGIN MODIFY BLOCK***
        ::The variables below should be modified to the
        ::files to be changed and the strings to find/replace
        ::Include trailing backslash in _FilePath
        set _FilePath=PathToFile
        set _FileName=FileNameToModify
        ::_WrkFile is the file on which the script will make
        ::modifications.
        set _WrkFile=BackupFileName
        set OldStr="The string to be found and replaced, enclosed in double-quotes"
        set NewStr="The new string to replace the value of OldStr, enclosed in double-quotes"
        ::***END MODIFY BLOCK***

        ::Set a variable which is used by the
        ::search and replace section to let us
        ::know if the string to be modified was
        ::found or not.
        set _Found=Not found

        SETLOCAL
        SETLOCAL ENABLEDELAYEDEXPANSION

        if not exist "%_FilePath%%_FileName%" goto :NotFound

        ::If a backup file exists, delete it
        if exist "%_FilePath%%_WrkFile%" (
        echo Deleting "%_FilePath%%_WrkFile%"
        del "%_FilePath%%_WrkFile%" >nul 2>&1
        )

        echo.
        echo Backing up "%_FilePath%%_FileName%"...
        copy "%_FilePath%%_FileName%" "%_FilePath%%_WrkFile%" /v

        ::Delete the original file. No worries, we got a backup.
        if exist "%_FilePath%%_FileName%" del "%_FilePath%%_FileName%"
        echo.
        echo Searching for %OldStr% string...
        echo.
        for /f "usebackq tokens=*" %%a in ("%_FilePath%%_WrkFile%") do (
        set _LineChk=%%a
        if "!_LineChk!"==%OldStr% (
        SET _Found=Found
        SET NewStr=!NewStr:^"=!
        echo !NewStr!
        ) else (echo %%a)
        )>>"%_FilePath%%_FileName%" 2>&1

        ::If we didn't find the string, rename the backup file to the original file name
        ::Otherwise, delete the _WorkFile as we re-created the original file when the
        ::string was found and replaced.
        if /i "!_Found!"=="Not found" (echo !_Found! && del "%_FilePath%%_FileName%" && ren "%_FilePath%%_WrkFile%" %_FileName%) else (echo !_Found! && del "%_FilePath%%_WrkFile%")
        goto :exit

        :NotFound
        echo.
        echo File "%_FilePath%%_FileName%" missing.
        echo Cannot continue...
        echo.
        :: Pause script for approx. 10 seconds...
        PING 127.0.0.1 -n 11 > NUL 2>&1
        goto :Exit

        :Exit
        exit /b





        share|improve this answer














        See if this helps. I had this from when I needed to perform a search and replace on an XML file. The strings, as long as you enclose them in double-quotes, can have special characters such as greater than and less than (used as redirection by scripts, ignored here). If you don't like the usage of variables to define the files you want to modify, you could make them into arguments which you could pass to the script. But then you would have to change the logic to shift the parameters unless you explicitly say "parameter 1 is the file to be changed, parameter 2 is the string to be found, etc..."



        Hope this helps someone. Windows XP or higher is required.



        ::Find and Replace script allows the user to 
        ::define a file path, file name and a string
        ::to find and replace so as to create a new file.
        ::
        ::Original file is backed up with an added extension of *.bak, in case
        ::the user finds the need to go back to the original.

        @echo off
        ::Use the path from whence the script was executed as
        ::the Current Working Directory
        set CWD=%~dp0

        ::***BEGIN MODIFY BLOCK***
        ::The variables below should be modified to the
        ::files to be changed and the strings to find/replace
        ::Include trailing backslash in _FilePath
        set _FilePath=PathToFile
        set _FileName=FileNameToModify
        ::_WrkFile is the file on which the script will make
        ::modifications.
        set _WrkFile=BackupFileName
        set OldStr="The string to be found and replaced, enclosed in double-quotes"
        set NewStr="The new string to replace the value of OldStr, enclosed in double-quotes"
        ::***END MODIFY BLOCK***

        ::Set a variable which is used by the
        ::search and replace section to let us
        ::know if the string to be modified was
        ::found or not.
        set _Found=Not found

        SETLOCAL
        SETLOCAL ENABLEDELAYEDEXPANSION

        if not exist "%_FilePath%%_FileName%" goto :NotFound

        ::If a backup file exists, delete it
        if exist "%_FilePath%%_WrkFile%" (
        echo Deleting "%_FilePath%%_WrkFile%"
        del "%_FilePath%%_WrkFile%" >nul 2>&1
        )

        echo.
        echo Backing up "%_FilePath%%_FileName%"...
        copy "%_FilePath%%_FileName%" "%_FilePath%%_WrkFile%" /v

        ::Delete the original file. No worries, we got a backup.
        if exist "%_FilePath%%_FileName%" del "%_FilePath%%_FileName%"
        echo.
        echo Searching for %OldStr% string...
        echo.
        for /f "usebackq tokens=*" %%a in ("%_FilePath%%_WrkFile%") do (
        set _LineChk=%%a
        if "!_LineChk!"==%OldStr% (
        SET _Found=Found
        SET NewStr=!NewStr:^"=!
        echo !NewStr!
        ) else (echo %%a)
        )>>"%_FilePath%%_FileName%" 2>&1

        ::If we didn't find the string, rename the backup file to the original file name
        ::Otherwise, delete the _WorkFile as we re-created the original file when the
        ::string was found and replaced.
        if /i "!_Found!"=="Not found" (echo !_Found! && del "%_FilePath%%_FileName%" && ren "%_FilePath%%_WrkFile%" %_FileName%) else (echo !_Found! && del "%_FilePath%%_WrkFile%")
        goto :exit

        :NotFound
        echo.
        echo File "%_FilePath%%_FileName%" missing.
        echo Cannot continue...
        echo.
        :: Pause script for approx. 10 seconds...
        PING 127.0.0.1 -n 11 > NUL 2>&1
        goto :Exit

        :Exit
        exit /b






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 3 at 0:58









        JakeGould

        30.9k1093137




        30.9k1093137










        answered Jan 17 '14 at 16:51









        JSanchez

        1,51289




        1,51289
























            up vote
            0
            down vote













            This should do the trick:



            $filepath = "C:Program FilesEqualizerAPOconfigconfig.txt";
            $equalizer = "";
            $equalizers = @("Headphones","Surround","Theater"); # Add all options here.

            if( -not (test-path $filepath))
            {
            Write-Host "File: `"$filepath`" not found";
            exit(1);
            }


            if($args.count -gt 0)
            {
            if($args[0] -ge 0 -and $args[0] -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$args[0]];
            }
            elseif($equalizers -contains $args[0])
            {
            $equalizer = $args[0];
            }
            else
            {
            Write-Host "Invalid argument";
            exit(1);
            }
            }
            else
            {
            Write-Host "Select from the following equalizers:";

            $i=0;

            foreach( $option in $equalizers)
            {
            Write-Host "$i. $option";
            $i++;
            }
            $choice = Read-Host "Enter choice:";

            if($choice -ge 0 -and $choice -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$choice];
            }
            else
            {
            Write-Host "Invalid choice";
            exit(1);
            }
            }

            Write-Host "Changing config file to use $equalizer";

            (Get-Content $filepath) | %{

            $_ -replace '^Include: .*$', ("Include: $equalizer.txt")

            } | Set-Content $filepath

            exit(0);


            Save as filename.ps1 and create a bat file named filename.cmd and place them both somewhere in your PATH, that way you can run the script by typing "filename" in either windows start menu or run.



            paste the following in the bat file:



            @echo off
            if [%1]== goto none
            powershell "& '%~dp0filename.ps1' '%1'"
            goto end
            :none
            powershell "& '%~dp0filename.ps1'"
            :end


            PS: if you havent before be sure to enable running of powershell scripts:



            powershell "set-executionpolicy remotesigned"





            share|improve this answer





















            • You should state at the beginning of your question that the code that follows is not a batch file. apart from 7 lines at the end
              – barlop
              Nov 5 '15 at 12:59

















            up vote
            0
            down vote













            This should do the trick:



            $filepath = "C:Program FilesEqualizerAPOconfigconfig.txt";
            $equalizer = "";
            $equalizers = @("Headphones","Surround","Theater"); # Add all options here.

            if( -not (test-path $filepath))
            {
            Write-Host "File: `"$filepath`" not found";
            exit(1);
            }


            if($args.count -gt 0)
            {
            if($args[0] -ge 0 -and $args[0] -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$args[0]];
            }
            elseif($equalizers -contains $args[0])
            {
            $equalizer = $args[0];
            }
            else
            {
            Write-Host "Invalid argument";
            exit(1);
            }
            }
            else
            {
            Write-Host "Select from the following equalizers:";

            $i=0;

            foreach( $option in $equalizers)
            {
            Write-Host "$i. $option";
            $i++;
            }
            $choice = Read-Host "Enter choice:";

            if($choice -ge 0 -and $choice -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$choice];
            }
            else
            {
            Write-Host "Invalid choice";
            exit(1);
            }
            }

            Write-Host "Changing config file to use $equalizer";

            (Get-Content $filepath) | %{

            $_ -replace '^Include: .*$', ("Include: $equalizer.txt")

            } | Set-Content $filepath

            exit(0);


            Save as filename.ps1 and create a bat file named filename.cmd and place them both somewhere in your PATH, that way you can run the script by typing "filename" in either windows start menu or run.



            paste the following in the bat file:



            @echo off
            if [%1]== goto none
            powershell "& '%~dp0filename.ps1' '%1'"
            goto end
            :none
            powershell "& '%~dp0filename.ps1'"
            :end


            PS: if you havent before be sure to enable running of powershell scripts:



            powershell "set-executionpolicy remotesigned"





            share|improve this answer





















            • You should state at the beginning of your question that the code that follows is not a batch file. apart from 7 lines at the end
              – barlop
              Nov 5 '15 at 12:59















            up vote
            0
            down vote










            up vote
            0
            down vote









            This should do the trick:



            $filepath = "C:Program FilesEqualizerAPOconfigconfig.txt";
            $equalizer = "";
            $equalizers = @("Headphones","Surround","Theater"); # Add all options here.

            if( -not (test-path $filepath))
            {
            Write-Host "File: `"$filepath`" not found";
            exit(1);
            }


            if($args.count -gt 0)
            {
            if($args[0] -ge 0 -and $args[0] -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$args[0]];
            }
            elseif($equalizers -contains $args[0])
            {
            $equalizer = $args[0];
            }
            else
            {
            Write-Host "Invalid argument";
            exit(1);
            }
            }
            else
            {
            Write-Host "Select from the following equalizers:";

            $i=0;

            foreach( $option in $equalizers)
            {
            Write-Host "$i. $option";
            $i++;
            }
            $choice = Read-Host "Enter choice:";

            if($choice -ge 0 -and $choice -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$choice];
            }
            else
            {
            Write-Host "Invalid choice";
            exit(1);
            }
            }

            Write-Host "Changing config file to use $equalizer";

            (Get-Content $filepath) | %{

            $_ -replace '^Include: .*$', ("Include: $equalizer.txt")

            } | Set-Content $filepath

            exit(0);


            Save as filename.ps1 and create a bat file named filename.cmd and place them both somewhere in your PATH, that way you can run the script by typing "filename" in either windows start menu or run.



            paste the following in the bat file:



            @echo off
            if [%1]== goto none
            powershell "& '%~dp0filename.ps1' '%1'"
            goto end
            :none
            powershell "& '%~dp0filename.ps1'"
            :end


            PS: if you havent before be sure to enable running of powershell scripts:



            powershell "set-executionpolicy remotesigned"





            share|improve this answer












            This should do the trick:



            $filepath = "C:Program FilesEqualizerAPOconfigconfig.txt";
            $equalizer = "";
            $equalizers = @("Headphones","Surround","Theater"); # Add all options here.

            if( -not (test-path $filepath))
            {
            Write-Host "File: `"$filepath`" not found";
            exit(1);
            }


            if($args.count -gt 0)
            {
            if($args[0] -ge 0 -and $args[0] -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$args[0]];
            }
            elseif($equalizers -contains $args[0])
            {
            $equalizer = $args[0];
            }
            else
            {
            Write-Host "Invalid argument";
            exit(1);
            }
            }
            else
            {
            Write-Host "Select from the following equalizers:";

            $i=0;

            foreach( $option in $equalizers)
            {
            Write-Host "$i. $option";
            $i++;
            }
            $choice = Read-Host "Enter choice:";

            if($choice -ge 0 -and $choice -lt $equalizers.length)
            {
            $equalizer = $equalizers[[int]$choice];
            }
            else
            {
            Write-Host "Invalid choice";
            exit(1);
            }
            }

            Write-Host "Changing config file to use $equalizer";

            (Get-Content $filepath) | %{

            $_ -replace '^Include: .*$', ("Include: $equalizer.txt")

            } | Set-Content $filepath

            exit(0);


            Save as filename.ps1 and create a bat file named filename.cmd and place them both somewhere in your PATH, that way you can run the script by typing "filename" in either windows start menu or run.



            paste the following in the bat file:



            @echo off
            if [%1]== goto none
            powershell "& '%~dp0filename.ps1' '%1'"
            goto end
            :none
            powershell "& '%~dp0filename.ps1'"
            :end


            PS: if you havent before be sure to enable running of powershell scripts:



            powershell "set-executionpolicy remotesigned"






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 17 '14 at 18:38









            Martin

            1,19776




            1,19776












            • You should state at the beginning of your question that the code that follows is not a batch file. apart from 7 lines at the end
              – barlop
              Nov 5 '15 at 12:59




















            • You should state at the beginning of your question that the code that follows is not a batch file. apart from 7 lines at the end
              – barlop
              Nov 5 '15 at 12:59


















            You should state at the beginning of your question that the code that follows is not a batch file. apart from 7 lines at the end
            – barlop
            Nov 5 '15 at 12:59






            You should state at the beginning of your question that the code that follows is not a batch file. apart from 7 lines at the end
            – barlop
            Nov 5 '15 at 12:59




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Super User!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f700458%2flooking-to-create-a-batch-file-capable-of-editing-a-line-or-word-in-a-text-fil%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            flock() on closed filehandle LOCK_FILE at /usr/bin/apt-mirror

            Mangá

             ⁒  ․,‪⁊‑⁙ ⁖, ⁇‒※‌, †,⁖‗‌⁝    ‾‸⁘,‖⁔⁣,⁂‾
”‑,‥–,‬ ,⁀‹⁋‴⁑ ‒ ,‴⁋”‼ ⁨,‷⁔„ ‰′,‐‚ ‥‡‎“‷⁃⁨⁅⁣,⁔
⁇‘⁔⁡⁏⁌⁡‿‶‏⁨ ⁣⁕⁖⁨⁩⁥‽⁀  ‴‬⁜‟ ⁃‣‧⁕‮ …‍⁨‴ ⁩,⁚⁖‫ ,‵ ⁀,‮⁝‣‣ ⁑  ⁂– ․, ‾‽ ‏⁁“⁗‸ ‾… ‹‡⁌⁎‸‘ ‡⁏⁌‪ ‵⁛ ‎⁨ ―⁦⁤⁄⁕