Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: How to search & replace a string in text file using a batch file  (Read 101867 times)

0 Members and 3 Guests are viewing this topic.

H4ckRn00b

    Topic Starter


    Rookie

    Thanked: 2
    • Experience: Beginner
    • OS: Windows 7
    How to search & replace a string in text file using a batch file
    « on: November 17, 2019, 03:12:07 PM »
    I want to write a batch file which can look through a textfile and find a string and replace it with another string.
    This two string will not be variables. They will be permantly the same.

    Conceptually, it should do something like this

    • Open file FRUIT.TXT
      Find string APPLE
      Replace with PEAR
      Repeat this till end of the file
      Save FRUIT.TXT

    Thanks!

    DaveLembke



      Sage
    • Thanked: 662
    • Certifications: List
    • Computer: Specs
    • Experience: Expert
    • OS: Windows 10
    Re: How to search & replace a string in text file using a batch file
    « Reply #1 on: November 17, 2019, 04:44:16 PM »
    Is this a homework assignment?

    There is a method that was shared by Foxidrive that helped me with a replacement within text files but it was achieved by QBasic on an old Windows NT system, and not pure batch. More info at the link here if QBasic is an option.

    https://www.computerhope.com/forum/index.php?topic=151160.30


    nil

    • Global Moderator


    • Intermediate
    • Thanked: 15
      • Experience: Experienced
      • OS: Linux variant
      Re: How to search & replace a string in text file using a batch file
      « Reply #2 on: November 17, 2019, 04:53:28 PM »
      this answer from stackoverflow worked for me.

      https://stackoverflow.com/questions/2772456/string-replacement-in-batch-file/2772498

      for example

      C:\Users\nil\newfruit>type FRUIT.TXT
      APPLES ARE GOOD FOR YOU.
      I WANT TO EAT AN APPLE.

      C:\Users\nil\newfruit>type replace.vbs
      Const ForReading = 1
      Const ForWriting = 2

      strFileName = Wscript.Arguments(0)
      strOldText = Wscript.Arguments(1)
      strNewText = Wscript.Arguments(2)

      Set objFSO = CreateObject("Scripting.FileSystemObject")
      Set objFile = objFSO.OpenTextFile(strFileName, ForReading)

      strText = objFile.ReadAll
      objFile.Close
      strNewText = Replace(strText, strOldText, strNewText)

      Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
      objFile.Write strNewText
      objFile.Close

      C:\Users\nil\newfruit>cscript replace.vbs "FRUIT.TXT" "APPLE" "PEAR"
      Microsoft (R) Windows Script Host Version 5.812
      Copyright (C) Microsoft Corporation. All rights reserved.

      C:\Users\nil\newfruit>type FRUIT.TXT
      PEARS ARE GOOD FOR YOU.
      I WANT TO EAT AN PEAR.
      Do not communicate by sharing memory; instead, share memory by communicating.

      --Effective Go

      H4ckRn00b

        Topic Starter


        Rookie

        Thanked: 2
        • Experience: Beginner
        • OS: Windows 7
        Re: How to search & replace a string in text file using a batch file
        « Reply #3 on: November 17, 2019, 06:30:24 PM »
        Is this a homework assignment?
        Wow, such insults! i should reply with a biting comment..... about projection-projection-projection or something, but in order to de-escalate, I won't.

        I can see you've been infected by the arrogance-*censored*-baseless-suspicion virus that's so virulent on stackedOverflow. Don't let it spread to others.

        And Qbasic???? Please .............

        Geek-9pm


          Mastermind
        • Geek After Dark
        • Thanked: 1026
          • Gekk9pm bnlog
        • Certifications: List
        • Computer: Specs
        • Experience: Expert
        • OS: Windows 10
        Re: How to search & replace a string in text file using a batch file
        « Reply #4 on: November 17, 2019, 06:50:55 PM »
        Q basic is free and compatible with recent versions of Windows.
        In QBasic you would read the text into an array and then go through the array and find and replace strings. Rather starlight standard stuff people used to do years ago.
         forward.

        An there are other methods available. There are programs  do find and replace  inside a batch file Among these are things ported from UNIX  to Windows.

        BC_Programmer


          Mastermind
        • Typing is no substitute for thinking.
        • Thanked: 1140
          • Yes
          • Yes
          • BC-Programming.com
        • Certifications: List
        • Computer: Specs
        • Experience: Beginner
        • OS: Windows 11
        Re: How to search & replace a string in text file using a batch file
        « Reply #5 on: November 17, 2019, 08:12:53 PM »
        Dave asked if it was homework primarily because it was phrased much like a homework assignment. It's hardly an "insult", but it's useful to know because then answers can be catered to that. For homework, than the aim was to learn something. Being given a working solution won't help you if the same topic comes up later. Conversely, if the solution is needed for the task it performs, than it would simply be more important to have the "solution" - a working batch script- as learning is more "secondary" in that scenario.

        As to the problem.

        You can iterate through all the lines in a file using an appropriate "for /F" command.

        Code: [Select]
        setlocal enabledelayedexpansion
        for /F "tokens=*" %%A in (fruit.txt) do (
        echo %%A
        )


        You can use command prompt to replace text within an environment variable via set:

        Code: [Select]
        set line=%%A
        set result=%line:APPLE=PEAR%

        You can use >> and > to redirect echoed output to a file. With this problem I'd suggest a temporary output file, and after the for command finishes, erasing the original file and renaming the temporary file to the original name.

        From what I can tell, the replacement feature of "set" doesn't seem to work if the find or replacement text has spaces- not an issue here since APPLE and PEAR would be hard-coded as per the description, but worth considering if this will be expanded in some way.

        I was trying to dereference Null Pointers before it was cool.

        Allan

        • Moderator

        • Mastermind
        • Thanked: 1260
        • Experience: Guru
        • OS: Windows 10
        Re: How to search & replace a string in text file using a batch file
        « Reply #6 on: November 18, 2019, 05:25:02 AM »
        The only biting comments I see here are in your second post. You are new here and asking for assistance. You've received intelligent and helpful responses from some of our most respected members. I don't know what you are used to based on your experiences at other forums, but on this site we are here to offer help. Please accept that help with the same courtesy and respect with which it is offered.

        nil

        • Global Moderator


        • Intermediate
        • Thanked: 15
          • Experience: Experienced
          • OS: Linux variant
          Re: How to search & replace a string in text file using a batch file
          « Reply #7 on: November 18, 2019, 05:29:23 AM »
          The VBScript solution works for every version of Windows, without installing any software. I'll document it on the site.
          Do not communicate by sharing memory; instead, share memory by communicating.

          --Effective Go

          Salmon Trout

          • Guest
          Re: How to search & replace a string in text file using a batch file
          « Reply #8 on: November 18, 2019, 09:56:27 AM »

          You can use command prompt to replace text within an environment variable via set:

          Code: [Select]
          set line=%%A
          set result=%line:APPLE=PEAR%

          if  the variable line is assigned the value of a FOR metavariable, we're in a bracket block, and don't we need delayed expansion?

          « Last Edit: November 18, 2019, 10:10:09 AM by Salmon Trout »

          Salmon Trout

          • Guest
          Re: How to search & replace a string in text file using a batch file
          « Reply #9 on: November 18, 2019, 10:00:06 AM »
          From what I can tell, the replacement feature of "set" doesn't seem to work if the find or replacement text has spaces- not an issue here since APPLE and PEAR would be hard-coded as per the description, but worth considering if this will be expanded in some way.


          C:\Users\Mike>set string1=Mary had a little lamb

          C:\Users\Mike>echo %string1%
          Mary had a little lamb

          C:\Users\Mike>set string2=%string1:Mary=Peter%

          C:\Users\Mike>echo %string2%
          Peter had a little lamb

          C:\Users\Mike>set string3=%string1:Mary had=Peter wanted%

          C:\Users\Mike>echo %string3%
          Peter wanted a little lamb

          C:\Users\Mike>set string4=%string1:Mary=Peter, Paul and Mary%

          C:\Users\Mike>echo %string4%
          Peter, Paul and Mary had a little lamb

          C:\Users\Mike>set string5=%string1:Mary=Peter, Paul and Mary% && set string5=%string5:lamb=lamb each%

          C:\Users\Mike>echo %string5%
          Peter, Paul and Mary had a little lamb each



          Now you all know my name....
          « Last Edit: November 18, 2019, 10:18:33 AM by Salmon Trout »

          H4ckRn00b

            Topic Starter


            Rookie

            Thanked: 2
            • Experience: Beginner
            • OS: Windows 7
            Re: How to search & replace a string in text file using a batch file
            « Reply #10 on: November 18, 2019, 11:13:45 AM »
            for example

            I've customized/changed that script somewhat, into:

            Code: [Select]
            Const ForReading = 1
            Const ForWriting = 2
            Const FileIn = "FRUIT.TXT"
            Const FileOut = "FRUIT.TXT"

            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFile = objFSO.OpenTextFile(FileIn, ForReading)

            strText = objFile.ReadAll
            objFile.Close

            strNewText = Replace(strText, "OrangesApples", "LemonPears")
            strNewText = Replace(strText, "Apples", "Pears")

            Set objFile = objFSO.OpenTextFile(FileOut, ForWriting)
            objFile.WriteLine strNewText
            objFile.Close
            [/tt]

            Question 1: I've tried to make this script run at start up, with a batch file in the Startup folder, but somehow that doesn't work, it's only running if I execute it manually. How do I make it run a start up, for both Win7 and Win10?
            The first replacment line with "OrangesApples" and "LemonPears"  occurs just once at the beginning of the file, the 2nd replacment line with "Apples" and "Pears" occurs more frequently. And yes, it's a subset of the first line.

            Question 2: Your script is more complicated and/or longer. Why is that, what does it do different than the above script?

            Salmon Trout

            • Guest
            Re: How to search & replace a string in text file using a batch file
            « Reply #11 on: November 18, 2019, 11:18:54 AM »
            I can see you've been infected by the arrogance-*censored*-baseless-suspicion virus that's so virulent on stackedOverflow. Don't let it spread to others.

            I find with the various Stack Exchange sites I belong to, that you tend to get back roughly what you put in.

            H4ckRn00b

              Topic Starter


              Rookie

              Thanked: 2
              • Experience: Beginner
              • OS: Windows 7
              Re: How to search & replace a string in text file using a batch file
              « Reply #12 on: November 18, 2019, 11:29:36 AM »
              I find with the various Stack Exchange sites I belong to, that you tend to get back roughly what you put in.
              Well, not my experience. How's that ad line again? "YMMV".


              Salmon Trout

              • Guest
              Re: How to search & replace a string in text file using a batch file
              « Reply #13 on: November 18, 2019, 11:38:46 AM »
              That VBScript has a feature I don't like. It overwrites the input file. It's a bit late to find out it doesn't do what you want if you have obliterated your original data. At least it doesn't have lots of set [whatever]=Nothing lines at the end.

              Where did that script come from?

              As for Question 1, you can place a one-line batch script in your Startup folder

              cscript //nologo path/to/scriptname.vbs

              Change cscript to wscript if you don't want a console window.

              If you code the actual paths to the input and output .txt files in the script, you can put the .vbs script itself in the Startup folder.

              This all looks a bit shaky though. If this is corporate data in a work setting, should you be doing this?



              H4ckRn00b

                Topic Starter


                Rookie

                Thanked: 2
                • Experience: Beginner
                • OS: Windows 7
                Re: How to search & replace a string in text file using a batch file
                « Reply #14 on: November 18, 2019, 11:40:13 AM »

                C:\Users\Mike>set string5=%string1:Mary=Peter, Paul and Mary% && set string5=%string5:lamb=lamb each%

                C:\Users\Mike>echo %string5%
                Peter, Paul and Mary had a little lamb each


                While the gist of this last set command example is clear to me: (In one string, two parts are replaced), the details aren't so clear:
                Does it mean: In string1, replace 'Mary' with 'Peter, Paul and Mary' and then put that in string 5, and then, in the resulting string 5, replace 'lamb' with 'lamb each'? And what is the function of the double ampersand? concatenation, or something else?