• Search & Replace the contents of text file with batch script

    Home » Forums » AskWoody support » Windows » Windows – other » Search & Replace the contents of text file with batch script

    Author
    Topic
    #493153

    Hello,

    In a folder I have lots of subfolders and my range to modify the text file starts from subfolder 000 to 050 & leave all other subfolders. I want to modify the text file named data.txt from this subfolders 000 to 050
    Folder structure:
    D:ReceiptsZoneDD-MM-YYReport (DD-MM-YY todays date)
    000 (folder named ‘000’ contains the data.txt file to be modified)
    001 (folder named ‘001’ contains the data.txt file to be modified)
    002 (folder named ‘002’ contains the data.txt file to be modified)

    modification of text file is upto folder ‘050’.

    Needs to modify the text file from line no. 2 (leaving the first line its header). To modify the first 3 digits if its 302 then its fine and if its something else then 302 then modify it to 302.
    Example:
    some company xyz 27012013
    30287921xxxx
    30287822xxxx
    10387823xxxx <—- Replace the first three digits to 302.

    Desperately needs your help

    Viewing 7 reply threads
    Author
    Replies
    • #1436421

      Here’s my attempt at what you want.

      I am assuming
      * the BATch file (which I’ve called 302ify.bat) is place in the top level directory, which seems to be D:ReceiptsZoneDD-MM-YYReport (DD-MM-YY todays date)
      * each subdirectory 000,001 … 050 contains the file data.txt which you ant modified
      * data.txt contains lines without any nasty characters like % ^ & ” which can wreck BATch file reading
      * my logic, where I check the first three characters for numericity, entirely meets your requirements
      * you will have to delete the data.ori (original version of data.txt) when you’re happy with the results
      * if the data.txt files are large, processing may be slow

      I’ve tested it on a couple of directories based on your example lines.
      I assume you know enough about BATch files to be able to read the code and add in PAUSE and ECHO statements if you wish.

      As always, it might be a pretty neat idea to do a backup of all the folders somewhere else, in case I haven’t thought of something!

      Code:
      @echo off
      
      :: 302ify.bat
      :: ----------
      
      :: this BATch file should be placed in the top level directory/folder below
      ::   which are the folders 000-050, whose data.txt file is to be changed
      
      setlocal
      
      :: process each folder in turn
      for /l %%a in (0, 1, 50) do call :process_folder %%a
      
      echo Finished!
      endlocal
      :: end of BATch file
      goto :eof
      ::----------------
      
      :process_folder
      :: form the correct folder name with leading zeros
      set folder=00%1
      set folder=%folder:~-3,3%
      echo %~n0: processing folder %folder%
      
      :: set up the current directory
      pushd %folder%
      
      :: rename the original data.txt file to act as the source
      if not exist data.ori ren data.txt data.ori
      :: get rid of any processed data.txt from a previous run, if any
      if     exist data.txt del data.txt
      
      :: process the copied file data.ori one line at a time
      for /f "tokens=*" %%a in (data.ori) do call :process_line "%%a"
      
      :: end of folder processing
      popd
      goto :eof
      ::----------------
      
      :process_line
      :: remove the double-quotes from both ends of the line  
      set line=%~1
      
      :: here we assume that ONLY lines whose first three characters are numeric are to be changed
      :: split the line into two parts
      set firstthree=%line:~0,3%
      set remainder=%line:~3%
      
      :: process line according to first three characters
      set notnum=
      for /f "delims=0123456789" %%a in ("%firstthree%") do set notnum=y
      if defined notnum (
        rem first three characters are not numeric, just write out entire line
        echo %line%>> data.txt
        ) else (
        rem  first three characters are numeric, change them to 302
        echo 302%remainder%>> data.txt
      )
      
      :: end of line processing
      goto :eof
      

      BATcher

      Plethora means a lot to me.

    • #1436467

      Hi,

      Thanks a lot BATcher for script.

      It works perfectly. many Thanks.

      • #1436500

        I’ve used SSR to do this sort of thing – beats writing it yourself.

        cheers, Paul

        • #1436512

          I’ve used SSR to do this sort of thing – beats writing it yourself.
          cheers, Paul

          Sorry for me nothing beats writing it yourself! YMMV 😆 :cheers:

          May the Forces of good computing be with you!

          RG

          PowerShell & VBA Rule!
          Computer Specs

        • #1436530

          I’ve used SSR to do this sort of thing – beats writing it yourself.

          I nearly suggested GREP, but that will only process a single file in a single directory, and I assume the same applies for SSR (useful tool though it looks!). So some calling BATch file would probably be needed anyway.

          Ex-mainframe people might well have used SELCOPY a few years ago to do much the same sort of thing.

          BATcher

          Plethora means a lot to me.

    • #1436491

      fjohan,

      Just for another way here’s a powershell script that will work.

      Code:
      
      param (
        [Parameter(Mandatory=$True)]
          [string] $RptDte
      )
      
      [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
      [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
      
      Clear-Host
      $filecnt = 0
       $DriveDirPath  = "D:ReceiptsZone$RptDteReport" 
      
             Foreach ($f in dir "$DriveDirPathdata.txt" -Recurse) {
                 $Lines = (get-content $f) 
                 for ($cnt = 1; $cnt -lt $Lines.count; $cnt++) {
                   $x = $line.tostring()
                   $y = $x.substring(3) 
                   $Lines[$cnt] = "302$y"
                 }
                 $lines | set-content $f
                $filecnt++
             }
      
             $Message = "$filecnt File(s) were processed."
             
      
      [void] [Windows.Forms.MessageBox]::Show("$Message", "Completion Status", 
             [Windows.Forms.MessageBoxButtons]::OK , 
             [Windows.Forms.MessageBoxIcon]::Information) 
      

      If you place it in a directory called Scripts you can create a shortcut with the following target.
      C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe G:BEKDocsScriptsSubstText.ps1
      Replacing the part in bold to match your machine.
      The program will prompt you for the date:
      36141-PS
      If you haven’t used powershell before you will need to start powershell manually and enter this command:
      Set-ExecutionPolicy = RemoteSigned
      You can check it was successful by entering Get-ExecutionPolicy
      HTH :cheers:

      36142-SubstText

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

      • #1436629

        fjohan,

        Just for another way here’s a powershell script that will work.

        Hi, RetiredGeek,

        I tried my hands on your powershell script it show an error on line 26 & 27.

        You cannot call a method on a null-valued expression.
        At C:AutoSubstText.ps1:26 char:14
        + $x = $line.tostring()
        + ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull

        You cannot call a method on a null-valued expression.
        At C:AutoSubstText.ps1:27 char:14
        + $y = $x.substring(3)
        + ~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull

    • #1436524

      The only way that can happen is if the line
      if exist data.txt del data.txt
      doesn’t work, so the new data is added to the end of the previous data in data.txt!

      The data.txt files don’t have any unusual attributes, like R or H, do they?

      BATcher

      Plethora means a lot to me.

    • #1436536

      Hi,

      Thanks a lot for every one for wholeheartedly support.

      BATcher it works perfectly, I have edited my second post.

      Thanks.

    • #1436537

      Excellent; I tried my tests again but couldn’t replicate the problem that you encountered…!

      Without the “helpful comments” it was less than 30 lines of code.

      BATcher

      Plethora means a lot to me.

    • #1436648

      Fjohan,

      Sorry about that I did test it and it worked but I must have made changes after the last change.
      In this version I’ve also allowed for there to be blank lines in the file which was not in the original code.

      Code:
      
      param (
        [Parameter(Mandatory=$True)]
          [string] $RptDte
      )
      
      [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
      [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
      
      Clear-Host
      $filecnt = 0
      $DriveDirPath  = "D:ReceiptsZone$RptDteReport" 
      
             Foreach ($f in dir "$DriveDirPathdata.txt" -Recurse) {
                 $Lines = (get-content $f) 
                 for ($cnt = 1; $cnt -lt $Lines.count; $cnt++) {
                   if($Lines[$cnt]) {  #Check for Null line!
                      $x = $lines[$cnt].tostring()
                      $y = $x.substring(3) 
                      $Lines[$cnt] = "302$y"
                   }
                 }
                 $lines | set-content $f
                $filecnt++
             }
      
             $Message = "$filecnt File(s) were processed."
             
      
      [void] [Windows.Forms.MessageBox]::Show("$Message", "Completion Status", 
             [Windows.Forms.MessageBoxButtons]::OK , 
             [Windows.Forms.MessageBoxIcon]::Information)
      

      HTH :cheers:

      36148-SubstText

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1436655

      I had a similar problem, and I used Excel. I first copied the names into a file using the DOS pipe command (>filename.txt).

      I then imported the file (about a thousand names) into Excel, and manipulated it to my needs. I had to sequentially number them, so after I arranged them I used Excel to create a sequential number in an adjacent column.

      I then copied the information into another column, using a concatanation technique and the rename command (=”REN”&[appropriate cell]&…….). I copied that column of cells and “pasted special” the values onto a separate sheet and saved that as a text file. I named the file with a “BAT” extension. I ran that batch file, and it really worked quickly and neatly.

    Viewing 7 reply threads
    Reply To: Search & Replace the contents of text file with batch script

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: