Results 1 to 15 of 15
  1. #1
    New Lounger
    Join Date
    Oct 2013
    Posts
    23
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Search & Replace the contents of text file with batch script

    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:\Receipts\Zone\DD-MM-YY\Report (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

  2. #2
    Super Moderator BATcher's Avatar
    Join Date
    Feb 2008
    Location
    A cultural area in SW England
    Posts
    3,484
    Thanks
    34
    Thanked 201 Times in 180 Posts
    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:\Receipts\Zone\DD-MM-YY\Report (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

    "The trouble with quotes on the internet is that you can never know if they are genuine."
    Abraham Lincoln
    

  3. #3
    New Lounger
    Join Date
    Oct 2013
    Posts
    23
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Hi,

    Thanks a lot BATcher for script.

    It works perfectly. many Thanks.
    Last edited by fjohan; 2014-01-30 at 13:46.

  4. #4
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,731
    Thanks
    395
    Thanked 1,533 Times in 1,390 Posts
    fjohan,

    Just for another way here's a powershell script that will work.
    Code:
    <#+-----------------------------------------------------------------------+
      | PowerShell Pgm: SubstText.ps1                                         |
      | Programmed By : The Computer Mentor aka RetiredGeek                   |
      | Created       : 31 Jan 2014                                           |
      | Last Updated  :                                                       |
      | Current Ver.  : 1.0                                                   |
      +-----------------------------------------------------------------------+
    #>
    
    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:\Receipts\Zone\$RptDte\Report" 
    
           Foreach ($f in dir "$DriveDirPath\data.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:\WINDOWS\system32\WindowsPowerShell\v1.0\powersh ell.exe G:\BEKDocs\Scripts\SubstText.ps1
    Replacing the part in bold to match your machine.
    The program will prompt you for the date:
    PS.JPG
    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

    SubstText.zip
    Last edited by RetiredGeek; 2014-01-30 at 11:28.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  5. #5
    WS Lounge VIP
    Join Date
    Dec 2009
    Location
    Earth
    Posts
    8,625
    Thanks
    56
    Thanked 1,057 Times in 985 Posts
    numericity?

    cheers, Paul

  6. #6
    WS Lounge VIP
    Join Date
    Dec 2009
    Location
    Earth
    Posts
    8,625
    Thanks
    56
    Thanked 1,057 Times in 985 Posts
    I've used SSR to do this sort of thing - beats writing it yourself.

    cheers, Paul

  7. #7
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,731
    Thanks
    395
    Thanked 1,533 Times in 1,390 Posts
    Quote Originally Posted by Paul T View Post
    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
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  8. #8
    Super Moderator BATcher's Avatar
    Join Date
    Feb 2008
    Location
    A cultural area in SW England
    Posts
    3,484
    Thanks
    34
    Thanked 201 Times in 180 Posts
    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

    "The trouble with quotes on the internet is that you can never know if they are genuine."
    Abraham Lincoln
    

  9. #9
    Super Moderator BATcher's Avatar
    Join Date
    Feb 2008
    Location
    A cultural area in SW England
    Posts
    3,484
    Thanks
    34
    Thanked 201 Times in 180 Posts
    Quote Originally Posted by Paul T View Post
    numericity?
    numericity: The quality of being numeric.
    BATcher

    "The trouble with quotes on the internet is that you can never know if they are genuine."
    Abraham Lincoln
    

  10. #10
    Super Moderator BATcher's Avatar
    Join Date
    Feb 2008
    Location
    A cultural area in SW England
    Posts
    3,484
    Thanks
    34
    Thanked 201 Times in 180 Posts
    Quote Originally Posted by Paul T View Post
    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

    "The trouble with quotes on the internet is that you can never know if they are genuine."
    Abraham Lincoln
    

  11. #11
    New Lounger
    Join Date
    Oct 2013
    Posts
    23
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Hi,

    Thanks a lot for every one for wholeheartedly support.

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

    Thanks.

  12. #12
    Super Moderator BATcher's Avatar
    Join Date
    Feb 2008
    Location
    A cultural area in SW England
    Posts
    3,484
    Thanks
    34
    Thanked 201 Times in 180 Posts
    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

    "The trouble with quotes on the internet is that you can never know if they are genuine."
    Abraham Lincoln
    

  13. #13
    New Lounger
    Join Date
    Oct 2013
    Posts
    23
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by RetiredGeek View Post
    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:\Auto\SubstText.ps1:26 char:14
    + $x = $line.tostring()
    + ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: ( [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

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

  14. #14
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,731
    Thanks
    395
    Thanked 1,533 Times in 1,390 Posts
    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:
    <#+-----------------------------------------------------------------------+
      | PowerShell Pgm: SubstText.ps1                                         |
      | Programmed By : The Computer Mentor aka RetiredGeek                   |
      | Created       : 30 Jan 2014                                           |
      | Last Updated  : 31 Jan 2014                                                      |
      | Current Ver.  : 1.1                                                   |
      +-----------------------------------------------------------------------+
    #>
    
    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:\Receipts\Zone\$RptDte\Report" 
    
           Foreach ($f in dir "$DriveDirPath\data.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

    SubstText.zip
    Last edited by RetiredGeek; 2014-01-31 at 11:06.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  15. #15
    2 Star Lounger
    Join Date
    Feb 2008
    Posts
    103
    Thanks
    13
    Thanked 0 Times in 0 Posts
    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.
    [I have been here for years; I had to get things restarted]

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •