What exactly are you trying to do? Just read the file contents and replace text for later processing? Or write the changes back to the original file?
If it's the former, just read the file line by line, replacing the contents as needed. For example, if you have the following in test.txt:
chris-blah1
chris-blah2
chris-blah3
connor-blah4
And you want to replace "chris" with CHRIIIIS, read the contents into a variable. Then run a replace on it:
create directory tmp as '/tmp';
declare
f utl_file.file_type;
buffer varchar2(100);
begin
f := utl_file.fopen('TMP', 'test.txt', 'r');
loop
begin
utl_file.get_line(f, buffer, 100);
buffer := replace (buffer, 'chris', 'CHRIIIIS');
dbms_output.put_line(buffer);
exception
when no_data_found then exit;
end;
end loop;
utl_file.fclose(f);
end;
/
CHRIIIIS-blah1
CHRIIIIS-blah2
CHRIIIIS-blah3
connor-blah4
If you want to update the file itself things are trickier. There isn't an in-place overwrite option in utl_file. Instead, what you could do is:
- Open the file and also create a temporary file
- Read the file line-by-line
- Replace the text as needed, then write this to the temp file
- Once finished, rename the temp file to the original, overwriting the source
declare
f utl_file.file_type;
ftmp utl_file.file_type;
buffer varchar2(100);
begin
f := utl_file.fopen('TMP', 'test.txt', 'r');
ftmp := utl_file.fopen('TMP', 'test.txt.tmp', 'w');
loop
begin
utl_file.get_line(f, buffer, 100);
buffer := replace (buffer, 'chris', 'CHRIIIIS');
dbms_output.put_line(buffer);
utl_file.put_line(ftmp, buffer);
exception
when no_data_found then exit;
end;
end loop;
utl_file.fclose(f);
utl_file.fclose(ftmp);
utl_file.frename('TMP', 'test.txt.tmp', 'TMP', 'test.txt', true);
end;
/
CHRIIIIS-blah1
CHRIIIIS-blah2
CHRIIIIS-blah3
connor-blah4
You should now have a single test.txt file with the contents shown above.