LB Booster
« A Replace Ascii Text Command Line module »

Welcome Guest. Please Login or Register.
Apr 1st, 2018, 03:47am



ATTENTION MEMBERS: Conforums will be closing it doors and discontinuing its service on April 15, 2018.
We apologize Conforums does not have any export functions to migrate data.
Ad-Free has been deactivated. Outstanding Ad-Free credits will be reimbursed to respective payment methods.

Thank you Conforums members.
Speed up Liberty BASIC programs by up to ten times!
Compile Liberty BASIC programs to compact, standalone executables!
Overcome many of Liberty BASIC's bugs and limitations!
LB Booster Resources
LB Booster documentation
LB Booster Home Page
LB Booster technical Wiki
Just BASIC forum
BBC BASIC Home Page
Liberty BASIC forum (the original)

« Previous Topic | Next Topic »
Pages: 1  Notify Send Topic Print
 thread  Author  Topic: A Replace Ascii Text Command Line module  (Read 460 times)
terciops
New Member
Image


member is offline

Avatar




PM

Gender: Male
Posts: 5
xx A Replace Ascii Text Command Line module
« Thread started on: Mar 22nd, 2014, 6:06pm »

I recently set some 'homework' for my little 'programming class' at work. We were discussing the excellent article about 'Minimalist Documentation and meaningful variable names'

http://www.codeproject.com/Articles/236430/Minimalist-Coding-Guidelines

Anyway, the topic morphed around to how best to modify an existing program's variables cleanly. The obvious solution of 'Find and Replace' came up, but I rather thought that a simple program could do the job more elegantly and teach some techniques at the same time. Particularly I could use this to introduce the concept of 'Command Line' modules.

If you have ever tried to write to the Command Line using LB as is, you will know that it is possible, but awkward. LBB however makes it all a breeze. Compiling with the "Create Console Application" box ticked does all the work for you - just use a PRINT statement. And now Richard has fixed CLS -bliss :)

Anyway, I had to produce a standard example to 'mark' with - so here it is. The original requirements were :

Input a text string to find and a text string to replace it with in every occurrence in a file.

If the original string search term is suffixed with a * then replace after that point (the * is removed) with the replacement string to End of Line. This is to modify INI files etc on the fly.

There are lots of other bells and whistles you could put on like multiple files and replacement terms, but I am going to set that as a problem to be solved in a separate program with a GUI that will call this command line module to do the various sequences.

Here is my standard. Over commented deliberately, but it seems to work rather well. Give it a run and if you can help with any improvements or find any bugs - I would be grateful.

You might also like to try your hand at a LBB calling program for multiple files and changes.

enjoy

Ken

Code:
' RAT - Replace ASCII and Text utility
' Homework Standard Code
' Command Line - RAT, original text, new text
' where filename defaults to present directory if non stated

' Auckland 21 Mar 2014

' RAT01 - Started 21 Mar 2014

Global True, False, QuietMode, ReplaceEOL                 ' Just 4 Globals
False = 0 : True = 1                                      ' Initialise them
NoMainWin                                                 ' No screen output wanted
if (CommandLine$ = "") or (CommandLine$ = "/?") then      ' No entry - no action - just show the command line structure
    call ShowCL                                           ' Show Command Line structure
    goto [exit]
end if    

FileName$ = word$(CommandLine$,1,",")                     ' Extract the file name
if FileName$ = "" then [exit]                             ' Nothing valid - exit
FilePath$ = GetFileDirectory$(FileName$)                  ' Get the path from the filename if any
FileName$ = mid$(FileName$,len(FilePath$) + 1)            ' Now extract the filename proper
if FilePath$ = "" then FilePath$ = DefaultDir$ + "\"      ' No path information - assume the present directory
if FileExists(FilePath$,FileName$) = False then           ' If this is not a valid file then 
    call PTS " ** File Not Found **"                         ' Show reason
    goto [exit]
end if

if FileExists(FilePath$,"temp.bin") = True then           ' Tidy up any old copies of temp.bin that might be hanging around
    kill "temp.bin"
end if
                                                          ' We get here with a valid filename and directory to work on.
                                                          ' Is there a second and third statement to operate with?
                                                          
FindText$ = word$(CommandLine$,2,",")                     ' Is there a string to find?
Replace$ = word$(CommandLine$,3,",")                      ' Is there a string to replace it with?
if (FindText$ = "") or (Replace$ = "") then               ' Both are required, otherwise
    call ShowCL                                           ' Show Command Line structure
    goto [exit]
end if
ReplaceEOL = False
if right$(FindText$,1) = "*" then
    ReplaceEOL = True
    FindText$ = left$(FindText$,len(FindText$) - 1)       ' strip the *
end if

QuietMode = False                                         ' Setup Quiet Mode
if upper$(word$(CommandLine$,4,",")) = "Q" then
    QuietMode = True
end if    

if (FindText$ = "") or (Replace$ = "") then [exit]        ' We need both terms otherwise exit
name FilePath$ + FileName$ as "temp.bin"                  ' rename the original file to temp.bin
open "temp.bin" for input as #filein                      ' Now open temp.bin for input
open FilePath$ + FileName$ for output as #fileout         ' And the original filename as a new file for output
call PTS "Working on - " + FilePath$ + Filename$          ' Show the File details

while eof(#filein) = 0                                    ' Now we can loop through the whole file to eof
    line input #filein, t$                                ' Take in the whole of the next line as t$
[multiloop]                                               ' loop point for multiple finds on a line
    if instr(t$,FindText$) <> 0 then                      ' Is the text we want to find on this line ?
        call PTS t$                                       ' Show original line
        t$ = ReplaceString$(t$,FindText$,Replace$)        ' It is - change FindText$ with Replace$
        call PTS t$                                       ' Show modified line
        call PTS ""                                       ' Separator
        if ReplaceEOL = False then [multiloop]            ' Check for other instances on this line if NOT in ReplaceEOL
    end if 
    print #fileout, t$                                    ' Finished with this line - save it to the original file name
wend                                                      ' The whole file is now processed
close #filein                                             ' Close the Input File
close #fileout                                            ' Close the Output File
kill "temp.bin"                                           ' Delete the temp file

[exit]                                                    ' Quit label
end                                                       ' Quit command

[unknownerror]                                            ' Come here for something wrong
print "Error Code is ", Err                               ' And show what it is
print "Error Desc is ", Err$                              ' Should never be needed :)
end


' Functions and Subs


function ReplaceString$(t$,f$,r$)                         ' Replace f$ with r$ in t$ - * to trigger EOL mode
    p = instr(t$,f$)                                      ' where is it ?
    if ReplaceEOL = False then 
        ReplaceString$ = left$(t$,p-1) + r$ + mid$(t$,len(f$)+ p)
    else
        ReplaceString$ = left$(t$,p + len(f$) - 1) + r$
    end if           
end function


function GetFileDirectory$(fn$)        ' Is there a preceeding directory structure attached to filename$ - return it if so
    d$ = "a"                           ' need something in here to start the while - wend
    FileDirectory$ = ""                ' Not really needed but be defensive
    count = 1                          ' Initialise the counter
                                       ' Run the while loop until we run out of words after a \
                                       ' Build up FileDirectory$ with the result and keep a count for word$ to step into the path
    while d$ <> ""                   
        d$ = word$(fn$,count,"\")
        if (instr(d$,".") <> 0) or (d$ = "") then exit while 
        GetFileDirectory$ = GetFileDirectory$ + d$ + "\"        
        count = count + 1               
        wend    
end function                           ' Returns FileDirectory$ with the full path ands final \ excluding filename


function FileExists(where$,fn$)        ' does a file exist as where$/fn$
    on error goto [nofile]             ' if the open input fails - go here
    FileExists= False                  ' Default value of False
    open where$ + fn$ for input as #t  ' Try to open the file. Jump to [nofile] on failure
    FileExists = True                  ' It didn't fail so make the result True
    close #t                           ' Close the file handle if it opened
[nofile]        
    on error goto [unknownerror]       ' reset the On Error label
  end function                         ' Returns FileExists as either True or False    
  
  ' *********************  Text Outputs  *********************
  sub PTS text$                        ' Print text$ to screen if NOT in Quiet Mode
    if QuietMode = False then print text$  
  end sub  
  
  
  sub ShowCL                           ' Print this if the command line structure is incorrect
    cls
    print "Command Line structure should be : "
    print "RAT.EXE  Filename, string_to_replace, replacement_string,[q]uiet [optional]"
    print ""
    print "If filename is absent a full path then current directory is assumed"
    print ""
    print "Example"
    print "To change all the occurrences of the string 'testme' to 'Test_Me' use :"
    print "RAT.EXE filename,testme,Test_Me"
    print ""
    print "RAT.EXE also has a replacement to EOL feature thus : "
    print "If last character of string_to_replace is a '*' then"
    print "replacement_string will replace characters to the end of line "
    print "with string_to_replace staying in place "
    print ""
    print "Example"
    print "To change the line : 'UseFixedPageUI = false' to a value of 'true'"
    print "would use the following command line :"
    print "RAT.EXE filename,UseFixedPageUI = *,true  (the * is removed)"
  end sub             
« Last Edit: Mar 22nd, 2014, 6:15pm by terciops » User IP Logged

Pages: 1  Notify Send Topic Print
« Previous Topic | Next Topic »

| |

This forum powered for FREE by Conforums ©
Terms of Service | Privacy Policy | Conforums Support | Parental Controls