Task

Replace every occurring instance of a piece of text in a group of text files with another one.



For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.




include c:\cxpl\codes;          \intrinsic 'code' declarations
string 0;                       \use zero-terminated strings
 
func StrLen(A);                 \Return number of characters in an ASCIIZ string
char A;
int  I;
for I:= 0 to -1>>1-1 do
    if A(I) = 0 then return I;
 
func StrFind(A, B);             \Search for ASCIIZ string A in string B
\Returns address of first occurrence of string A in B, or zero if A is not found
char A, B;                      \strings to be compared
int  LA, LB, I, J;
[LA:= StrLen(A);
LB:= StrLen(B);
for I:= 0 to LB-LA do
    [for J:= 0 to LA-1 do
        if A(J) # B(J+I) then J:= LA+1;
    if J = LA then return B+I;  \found
    ];
return 0;
];
 
proc ReplaceText(FileName);     \replace text in specified file
char FileName;
char Str(1_000_000), Hello, Bye, Pointer;
int  Handle, I, C;
[Handle:= FOpen(FileName, 0);   \get handle for input file
FSet(Handle, ^I);               \set device 3 input to file handle
OpenI(3);                       \initialize buffer pointers
I:= 0;
repeat  C:= ChIn(3);            \read file into memory
        Str(I):= C;
        I:= I+1;
until   C = $1A; \EOF
FClose(Handle);                 \release handle
 
Hello:= "Hello New York!";      \replacement text
Bye:=   "Goodbye London!";
Pointer:= StrFind(Bye, Str);
if Pointer \#0\ then            \overwrite (both strings are same length)
   for I:= 0 to 15-1 do Pointer(I):= Hello(I);
 
Handle:= FOpen(FileName, 1);    \get handle for output file
FSet(Handle, ^O);               \set device 3 output to file handle
OpenO(3);
I:= 0;
repeat  C:= Str(I);             \write file from memory
        I:= I+1;
        ChOut(3, C);
until   C = $1A; \EOF
Close(3);                       \flush output buffer
FClose(Handle);                 \release handle
];
 
int File, I;
[File:= ["Alpha.txt", "Beta.txt", "Gamma.txt", "Delta.txt"];
for I:= 0 to 4-1 do ReplaceText(File(I));
]