Globally replace text in several files: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 9: Line 9:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>L(fname) fs:list_dir(‘.’)
<syntaxhighlight lang="11l">L(fname) fs:list_dir(‘.’)
I fname.ends_with(‘.txt’)
I fname.ends_with(‘.txt’)
V fcontents = File(fname).read()
V fcontents = File(fname).read()
File(fname, ‘w’).write(fcontents.replace(‘Goodbye London!’, ‘Hello, New York!’))
File(fname, ‘w’).write(fcontents.replace(‘Goodbye London!’, ‘Hello, New York!’))
</syntaxhighlight>
</lang>


=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line, Ada.Directories;
<syntaxhighlight lang="ada">with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line, Ada.Directories;


procedure Global_Replace is
procedure Global_Replace is
Line 76: Line 76:
File_Replace(Ada.Command_Line.Argument(I), Pattern, Replacement);
File_Replace(Ada.Command_Line.Argument(I), Pattern, Replacement);
end loop;
end loop;
end Global_Replace;</lang>
end Global_Replace;</syntaxhighlight>


Ouput:
Ouput:
Line 98: Line 98:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>SetWorkingDir %A_ScriptDir% ; Change the working directory to the script's location
<syntaxhighlight lang="autohotkey">SetWorkingDir %A_ScriptDir% ; Change the working directory to the script's location
listFiles := "a.txt|b.txt|c.txt" ; Define a list of files in the current working directory
listFiles := "a.txt|b.txt|c.txt" ; Define a list of files in the current working directory
loop, Parse, listFiles, |
loop, Parse, listFiles, |
Line 108: Line 108:
fileAppend, %contents%, %A_LoopField% ; Re-create the file with new contents
fileAppend, %contents%, %A_LoopField% ; Re-create the file with new contents
}
}
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GLOBALLY_REPLACE_TEXT_IN_SEVERAL_FILES.AWK filename(s)
# syntax: GAWK -f GLOBALLY_REPLACE_TEXT_IN_SEVERAL_FILES.AWK filename(s)
BEGIN {
BEGIN {
Line 140: Line 140:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>


{{works with|gawk}}
{{works with|gawk}}
<lang awk>@include "readfile"
<syntaxhighlight lang="awk">@include "readfile"
BEGIN {
BEGIN {
while(++i < ARGC)
while(++i < ARGC)
print gensub("Goodbye London!","Hello New York!","g", readfile(ARGV[i])) > ARGV[i]
print gensub("Goodbye London!","Hello New York!","g", readfile(ARGV[i])) > ARGV[i]
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 154: Line 154:
Pass the files on the command line (i.e. <code>global-replace *.txt</code>).
Pass the files on the command line (i.e. <code>global-replace *.txt</code>).


<lang qbasic>CONST matchtext = "Goodbye London!"
<syntaxhighlight lang="qbasic">CONST matchtext = "Goodbye London!"
CONST repltext = "Hello New York!"
CONST repltext = "Hello New York!"
CONST matchlen = LEN(matchtext)
CONST matchlen = LEN(matchtext)
Line 191: Line 191:
WEND
WEND
L0 += 1
L0 += 1
WEND</lang>
WEND</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> FindThis$ = "Goodbye London!"
<syntaxhighlight lang="bbcbasic"> FindThis$ = "Goodbye London!"
ReplaceWith$ = "Hello New York!"
ReplaceWith$ = "Hello New York!"
Line 224: Line 224:
OSCLI "REN """ + tmpfile$ + """ """ + infile$ + """"
OSCLI "REN """ + tmpfile$ + """ """ + infile$ + """"
NEXT
NEXT
END</lang>
END</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stddef.h>
#include <stddef.h>
Line 301: Line 301:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>
<syntaxhighlight lang="csharp">
using System.Collections.Generic;
using System.Collections.Generic;
using System.IO;
using System.IO;
Line 319: Line 319:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <fstream>
<syntaxhighlight lang="cpp">#include <fstream>
#include <iterator>
#include <iterator>
#include <boost/regex.hpp>
#include <boost/regex.hpp>
Line 348: Line 348:
}
}
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>


Modern C++ version:
Modern C++ version:
<lang cpp>#include <regex>
<syntaxhighlight lang="cpp">#include <regex>
#include <fstream>
#include <fstream>


Line 369: Line 369:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn hello-goodbye [& more]
<syntaxhighlight lang="clojure">(defn hello-goodbye [& more]
(doseq [file more]
(doseq [file more]
(spit file (.replace (slurp file) "Goodbye London!" "Hello New York!"))))</lang>
(spit file (.replace (slurp file) "Goodbye London!" "Hello New York!"))))</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
<lang Lisp>
(defun hello-goodbye (files)
(defun hello-goodbye (files)
(labels ((replace-from-file (file)
(labels ((replace-from-file (file)
Line 394: Line 394:
(write-lines-to-file (replace-from-file file) file)))
(write-lines-to-file (replace-from-file file) file)))
(map nil #'replace-in-file files)))
(map nil #'replace-in-file files)))
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
{{works with|D|2}}
{{works with|D|2}}
<lang d>import std.file, std.array;
<syntaxhighlight lang="d">import std.file, std.array;


void main() {
void main() {
Line 405: Line 405:
write(fn, replace(cast(string)read(fn), from, to));
write(fn, replace(cast(string)read(fn), from, to));
}
}
}</lang>
}</syntaxhighlight>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{libheader| System.IoUtils}}
{{libheader| System.IoUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Globally_replace_text_in_several_files;
program Globally_replace_text_in_several_files;


Line 439: Line 439:
begin
begin
StringReplaceByFile('Goodbye London!', 'Hello New York!', ['a.txt', 'b.txt', 'c.txt']);
StringReplaceByFile('Goodbye London!', 'Hello New York!', ['a.txt', 'b.txt', 'c.txt']);
end.</lang>
end.</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( globally_replace_text ).
-module( globally_replace_text ).


Line 465: Line 465:
io:fwrite( "Error: Could not write ~p: ~p~n", [File, Error] ),
io:fwrite( "Error: Could not write ~p: ~p~n", [File, Error] ),
error.
error.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 491: Line 491:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System.IO
<syntaxhighlight lang="fsharp">open System.IO


[<EntryPoint>]
[<EntryPoint>]
Line 502: Line 502:
if content <> newContent then
if content <> newContent then
File.WriteAllText(name, newContent)
File.WriteAllText(name, newContent)
0</lang>
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.99 2019-10-06}}
{{works with|Factor|0.99 2019-10-06}}
<lang factor>USING: fry io.encodings.utf8 io.files kernel qw sequences
<syntaxhighlight lang="factor">USING: fry io.encodings.utf8 io.files kernel qw sequences
splitting ;
splitting ;


Line 517: Line 517:


qw{ a.txt b.txt c.txt }
qw{ a.txt b.txt c.txt }
"Goodbye London!" "Hello New York!" global-replace</lang>
"Goodbye London!" "Hello New York!" global-replace</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 526: Line 526:
The file to be altered cannot be changed "in-place", as by writing back an altered record even if the text replacement does not involve a change in length because such a facility is not available for text files that are read and written sequentially only. More accomplished file systems may well offer varying-length records with update possible even of longer or shorter new versions but standard Fortran does not demand such facilities. So, the altered content has to be written to a temporary file (or perhaps could be held in a capacious memory) which is then read back to overwrite the original file. It would be safer to rename the original file and write to a new version, but Fortran typically does not have access to any file renaming facilities and the task calls for an overwrite anyway. So, overwrite it is, which is actually a file delete followed by a write.
The file to be altered cannot be changed "in-place", as by writing back an altered record even if the text replacement does not involve a change in length because such a facility is not available for text files that are read and written sequentially only. More accomplished file systems may well offer varying-length records with update possible even of longer or shorter new versions but standard Fortran does not demand such facilities. So, the altered content has to be written to a temporary file (or perhaps could be held in a capacious memory) which is then read back to overwrite the original file. It would be safer to rename the original file and write to a new version, but Fortran typically does not have access to any file renaming facilities and the task calls for an overwrite anyway. So, overwrite it is, which is actually a file delete followed by a write.


Once equipped with a subroutine that applies a specified change to a named disc file, there is no difficulty in invoking it for a horde of disc files. A more civilised routine might make reports about the files assaulted and the number of changes, and also be prepared to report various oddities such as a file being available but not for WRITE. It is for this reason that the source file is opened with READWRITE even though it at that stage is only going to be read from.<lang Fortran> SUBROUTINE FILEHACK(FNAME,THIS,THAT) !Attacks a file!
Once equipped with a subroutine that applies a specified change to a named disc file, there is no difficulty in invoking it for a horde of disc files. A more civilised routine might make reports about the files assaulted and the number of changes, and also be prepared to report various oddities such as a file being available but not for WRITE. It is for this reason that the source file is opened with READWRITE even though it at that stage is only going to be read from.<syntaxhighlight lang="fortran"> SUBROUTINE FILEHACK(FNAME,THIS,THAT) !Attacks a file!
CHARACTER*(*) FNAME !The name of the file, presumed to contain text.
CHARACTER*(*) FNAME !The name of the file, presumed to contain text.
CHARACTER*(*) THIS !The text sought in each record.
CHARACTER*(*) THIS !The text sought in each record.
Line 590: Line 590:
END DO !On to the next.
END DO !On to the next.


END</lang>
END</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|BASIC}}
{{trans|BASIC}}
<lang freebasic>Const matchtext = "Goodbye London!"
<syntaxhighlight lang="freebasic">Const matchtext = "Goodbye London!"
Const repltext = "Hello New York!"
Const repltext = "Hello New York!"
Const matchlen = Len(matchtext)
Const matchlen = Len(matchtext)
Line 623: Line 623:
Wend
Wend
L0 += 1
L0 += 1
Wend</lang>
Wend</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 676: Line 676:
_, err = f.WriteAt(r, 0)
_, err = f.WriteAt(r, 0)
return
return
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
The module Data.List provides some useful functions: tails (constructs substrings dropping elements from the head of the list), isPrefixOf (checks if a string matches the beginning of another one) and elemIndices (gets the list indices of all elements matching a value).
The module Data.List provides some useful functions: tails (constructs substrings dropping elements from the head of the list), isPrefixOf (checks if a string matches the beginning of another one) and elemIndices (gets the list indices of all elements matching a value).
This code doesn't rewrite the files, it just returns the changes made to the contents of the files.
This code doesn't rewrite the files, it just returns the changes made to the contents of the files.
<lang Haskell>import Data.List (tails, elemIndices, isPrefixOf)
<syntaxhighlight lang="haskell">import Data.List (tails, elemIndices, isPrefixOf)


replace :: String -> String -> String -> String
replace :: String -> String -> String -> String
Line 702: Line 702:
f <- mapM readFile files
f <- mapM readFile files
return $ map (replace a1 a2) f
return $ map (replace a1 a2) f
</syntaxhighlight>
</lang>
This other version is more effective because it processes the string more lazily, replacing the text as it consumes the input string (the previous version was stricter because of "matches" traversing the whole list; that would force the whole string into memory, which could cause the system to run out of memory with large text files).
This other version is more effective because it processes the string more lazily, replacing the text as it consumes the input string (the previous version was stricter because of "matches" traversing the whole list; that would force the whole string into memory, which could cause the system to run out of memory with large text files).
<lang Haskell>replace :: Eq a => [a] -> [a] -> [a] -> [a]
<syntaxhighlight lang="haskell">replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace a b = go
replace a b = go
where
where
Line 711: Line 711:
go xxs@(x : xs)
go xxs@(x : xs)
| a `isPrefixOf` xxs = b <> go (drop w xxs)
| a `isPrefixOf` xxs = b <> go (drop w xxs)
| otherwise = x : go xs</lang>
| otherwise = x : go xs</syntaxhighlight>


and with different library imports, we could also write things like:
and with different library imports, we could also write things like:
<lang haskell>import Data.List (intercalate)
<syntaxhighlight lang="haskell">import Data.List (intercalate)
import Data.List.Split (splitOn)
import Data.List.Split (splitOn)


replace :: String -> String -> String -> String
replace :: String -> String -> String -> String
replace a b = intercalate b . splitOn a</lang>
replace a b = intercalate b . splitOn a</syntaxhighlight>




Line 735: Line 735:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
This example uses the Unicon stat function. It can be rewritten for Icon to aggregate the file in a reads loop.
This example uses the Unicon stat function. It can be rewritten for Icon to aggregate the file in a reads loop.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
globalrepl("Goodbye London","Hello New York","a.txt","b.txt") # variable args for files
globalrepl("Goodbye London","Hello New York","a.txt","b.txt") # variable args for files
end
end
Line 749: Line 749:
end
end


link strings # for replace</lang>
link strings # for replace</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 758: Line 758:
If <code>files</code> is a variable with the desired list of file names:
If <code>files</code> is a variable with the desired list of file names:


<lang j>require'strings'
<syntaxhighlight lang="j">require'strings'
(1!:2~rplc&('Goodbye London!';'Hello New York!')@(1!:1))"0 files</lang>
(1!:2~rplc&('Goodbye London!';'Hello New York!')@(1!:1))"0 files</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Minimalistic version, assumes default encoding.
Minimalistic version, assumes default encoding.
{{works with|Java|7}}
{{works with|Java|7}}
<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;
import java.nio.file.*;
import java.nio.file.*;


Line 779: Line 779:
}
}
}
}
}</lang>
}</syntaxhighlight>


In Java 11 the body could be shortened to:
In Java 11 the body could be shortened to:
<lang java>
<syntaxhighlight lang="java">
for (String fn : List.of("file1.txt","file2.txt")) {
for (String fn : List.of("file1.txt","file2.txt")) {
Path path = Path.of(fn);
Path path = Path.of(fn);
Line 788: Line 788:
Files.readString(path).replace("Goodbye London!", "Hello New York!"));
Files.readString(path).replace("Goodbye London!", "Hello New York!"));
}
}
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
{{works with|jq|1.5}}
{{works with|jq|1.5}}
jq delegates filename manipulation to the shell. For simplicity, in the following we assume the availability of `sponge` to simplify the mechanics of editing a file "in-place".
jq delegates filename manipulation to the shell. For simplicity, in the following we assume the availability of `sponge` to simplify the mechanics of editing a file "in-place".
<lang bash>for file
<syntaxhighlight lang="bash">for file
do
do
jq -Rr 'gsub($from; $to)' --arg from 'Goodbye London!' --arg to 'Hello New York!' "$file" |
jq -Rr 'gsub($from; $to)' --arg from 'Goodbye London!' --arg to 'Hello New York!' "$file" |
sponge "$file"
sponge "$file"
done</lang>
done</syntaxhighlight>


The jq filter used above is `gsub/2`, which however is designed for regular expressions. Here is a string-oriented alternative:
The jq filter used above is `gsub/2`, which however is designed for regular expressions. Here is a string-oriented alternative:
<lang jq>def gsubst($from; $to):
<syntaxhighlight lang="jq">def gsubst($from; $to):
($from | length) as $len
($from | length) as $len
| def g:
| def g:
index($from) as $ix
index($from) as $ix
| if $ix then .[:$ix] + $to + (.[($ix+$len):] | g) else . end;
| if $ix then .[:$ix] + $to + (.[($ix+$len):] | g) else . end;
g;</lang>
g;</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
'''For the demo, the code does not overwrite the samples, but creates a .new file.'''
'''For the demo, the code does not overwrite the samples, but creates a .new file.'''
<lang javascript>/* Global replace in Jsish */
<syntaxhighlight lang="javascript">/* Global replace in Jsish */
if (console.args.length == 0) {
if (console.args.length == 0) {
console.args.push('-');
console.args.push('-');
Line 830: Line 830:
}
}
} catch(err) { puts(err, 'processing', fn); }
} catch(err) { puts(err, 'processing', fn); }
}</lang>
}</syntaxhighlight>


To meet the task specification, change
To meet the task specification, change


<lang javascript>if (fn == 'stdin') fn = 'stdout'; else fn += '.new';</lang>
<syntaxhighlight lang="javascript">if (fn == 'stdin') fn = 'stdout'; else fn += '.new';</syntaxhighlight>


to
to


<lang javascript>if (fn == 'stdin') fn = 'stdout';</lang>
<syntaxhighlight lang="javascript">if (fn == 'stdin') fn = 'stdout';</syntaxhighlight>


removing the else clause. The code will then overwrite originals.
removing the else clause. The code will then overwrite originals.
Line 855: Line 855:
=={{header|Julia}}==
=={{header|Julia}}==
We will use Julia's built-in Perl-compatible [http://docs.julialang.org/en/latest/manual/strings/#regular-expressions regular-expressions]. Although we could read in the files line by line, it is simpler and probably faster to just read the whole file into memory (as text files are likely to fit into memory on modern computers).
We will use Julia's built-in Perl-compatible [http://docs.julialang.org/en/latest/manual/strings/#regular-expressions regular-expressions]. Although we could read in the files line by line, it is simpler and probably faster to just read the whole file into memory (as text files are likely to fit into memory on modern computers).
<lang julia>filenames = ["f1.txt", "f2.txt"]
<syntaxhighlight lang="julia">filenames = ["f1.txt", "f2.txt"]
for filename in filenames
for filename in filenames
txt = read(filename, String)
txt = read(filename, String)
Line 861: Line 861:
write(f, replace(txt, "Goodbye London!" => "Hello New York!"))
write(f, replace(txt, "Goodbye London!" => "Hello New York!"))
end
end
end</lang>
end</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.2.0
<syntaxhighlight lang="scala">// version 1.2.0


import java.io.File
import java.io.File
Line 878: Line 878:
println(f.readText())
println(f.readText())
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 892: Line 892:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9


local(files = array('f1.txt', 'f2.txt'))
local(files = array('f1.txt', 'f2.txt'))
Line 905: Line 905:
#file -> writebytes(#content)
#file -> writebytes(#content)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
nomainwin
nomainwin


Line 945: Line 945:
end if
end if
end function
end function
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>filenames = { "f1.txt", "f2.txt" }
<syntaxhighlight lang="lua">filenames = { "f1.txt", "f2.txt" }


for _, fn in pairs( filenames ) do
for _, fn in pairs( filenames ) do
Line 959: Line 959:
fp:write( str )
fp:write( str )
fp:close()
fp:close()
end</lang>
end</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>listOfFiles = {"a.txt", "b.txt", "c.txt"};
<syntaxhighlight lang="mathematica">listOfFiles = {"a.txt", "b.txt", "c.txt"};
Do[
Do[
filename = listOfFiles[[i]];
filename = listOfFiles[[i]];
Line 968: Line 968:
filetext = StringReplace[filetext, "Goodbye London!" -> "Hello New York!"];
filetext = StringReplace[filetext, "Goodbye London!" -> "Hello New York!"];
Export[filename, filetext, "Text"]
Export[filename, filetext, "Text"]
, {i, 1, Length[listOfFiles]}]</lang>
, {i, 1, Length[listOfFiles]}]</syntaxhighlight>
File b.txt before the code is run:
File b.txt before the code is run:
<pre>second file for the Globally replace text in several files problem.
<pre>second file for the Globally replace text in several files problem.
Line 985: Line 985:
=={{header|newLISP}}==
=={{header|newLISP}}==
{{works with|newLisp|10.7.5}}
{{works with|newLisp|10.7.5}}
<syntaxhighlight lang="newlisp">
<lang newLISP>
(define (replace-in-file filename this bythat)
(define (replace-in-file filename this bythat)
(set 'content (read-file filename))
(set 'content (read-file filename))
Line 1,000: Line 1,000:


(exit)
(exit)
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils


let fr = "Goodbye London!"
let fr = "Goodbye London!"
Line 1,009: Line 1,009:


for fn in ["a.txt", "b.txt", "c.txt"]:
for fn in ["a.txt", "b.txt", "c.txt"]:
fn.writeFile fn.readFile.replace(fr, to)</lang>
fn.writeFile fn.readFile.replace(fr, to)</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>class ReplaceAll {
<syntaxhighlight lang="objeck">class ReplaceAll {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
files := ["text1.txt", "text2.txt"];
files := ["text1.txt", "text2.txt"];
Line 1,021: Line 1,021:
};
};
}
}
}</lang>
}</syntaxhighlight>


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang progress>FUNCTION replaceText RETURNS LOGICAL (
<syntaxhighlight lang="progress">FUNCTION replaceText RETURNS LOGICAL (
i_cfile_list AS CHAR,
i_cfile_list AS CHAR,
i_cfrom AS CHAR,
i_cfrom AS CHAR,
Line 1,045: Line 1,045:
"Goodbye London!",
"Goodbye London!",
"Hello New York!"
"Hello New York!"
).</lang>
).</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
<lang pascal>Program StringReplace;
<syntaxhighlight lang="pascal">Program StringReplace;


uses
uses
Line 1,073: Line 1,073:
AllText.Destroy;
AllText.Destroy;
end;
end;
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang bash>perl -pi -e "s/Goodbye London\!/Hello New York\!/g;" a.txt b.txt c.txt</lang>
<syntaxhighlight lang="bash">perl -pi -e "s/Goodbye London\!/Hello New York\!/g;" a.txt b.txt c.txt</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Line 1,082: Line 1,082:
as hinted, you could probably improve on the error handling.<br>
as hinted, you could probably improve on the error handling.<br>
get_text is deliberately limited to 1GB, for larger files use a temporary file, a loop of gets/puts, and delete_file/rename_file at the end.
get_text is deliberately limited to 1GB, for larger files use a temporary file, a loop of gets/puts, and delete_file/rename_file at the end.
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">global_replace</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">file_list</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">global_replace</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">file_list</span><span style="color: #0000FF;">)</span>
Line 1,100: Line 1,100:
<span style="color: #004080;">sequence</span> <span style="color: #000000;">file_list</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"ctrace.out"</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">file_list</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"ctrace.out"</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">global_replace</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Goodbye London!"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Hello New York!"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">file_list</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">global_replace</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Goodbye London!"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Hello New York!"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">file_list</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(for File '(a.txt b.txt c.txt)
<syntaxhighlight lang="picolisp">(for File '(a.txt b.txt c.txt)
(call 'mv File (tmp File))
(call 'mv File (tmp File))
(out File
(out File
(in (tmp File)
(in (tmp File)
(while (echo "Goodbye London!")
(while (echo "Goodbye London!")
(prin "Hello New York!") ) ) ) )</lang>
(prin "Hello New York!") ) ) ) )</syntaxhighlight>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
{{trans|BASIC}}
{{trans|BASIC}}
<lang powerbasic>$matchtext = "Goodbye London!"
<syntaxhighlight lang="powerbasic">$matchtext = "Goodbye London!"
$repltext = "Hello New York!"
$repltext = "Hello New York!"


Line 1,134: Line 1,134:
INCR L0
INCR L0
WEND
WEND
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$listfiles = @('file1.txt','file2.txt')
$listfiles = @('file1.txt','file2.txt')
$old = 'Goodbye London!'
$old = 'Goodbye London!'
Line 1,144: Line 1,144:
(Get-Content $file).Replace($old,$new) | Set-Content $file
(Get-Content $file).Replace($old,$new) | Set-Content $file
}
}
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure GRTISF(List File$(), Find$, Replace$)
<syntaxhighlight lang="purebasic">Procedure GRTISF(List File$(), Find$, Replace$)
Protected Line$, Out$, OutFile$, i
Protected Line$, Out$, OutFile$, i
ForEach File$()
ForEach File$()
Line 1,178: Line 1,178:
EndIf
EndIf
Next
Next
EndProcedure</lang>
EndProcedure</syntaxhighlight>
Implementation
Implementation
<pre>NewList Xyz$()
<pre>NewList Xyz$()
Line 1,190: Line 1,190:
From [http://docs.python.org/library/fileinput.html Python docs]. (Note: in-place editing does not work for MS-DOS 8+3 filesystems.).
From [http://docs.python.org/library/fileinput.html Python docs]. (Note: in-place editing does not work for MS-DOS 8+3 filesystems.).


<lang python>import fileinput
<syntaxhighlight lang="python">import fileinput


for line in fileinput.input(inplace=True):
for line in fileinput.input(inplace=True):
print(line.replace('Goodbye London!', 'Hello New York!'), end='')
print(line.replace('Goodbye London!', 'Hello New York!'), end='')
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Code wrapped in a convenient script:
Code wrapped in a convenient script:
<lang racket>
<syntaxhighlight lang="racket">
#!/usr/bin/env racket
#!/usr/bin/env racket
#lang racket
#lang racket
Line 1,222: Line 1,222:
(begin (display-to-file text2 file #:exists 'replace)
(begin (display-to-file text2 file #:exists 'replace)
(printf " modified copy saved in place\n")))))
(printf " modified copy saved in place\n")))))
</syntaxhighlight>
</lang>
Sample run:
Sample run:
<pre>
<pre>
Line 1,245: Line 1,245:
Current Raku implementations do not yet support the -i flag for editing files in place, so we roll our own (rather unsafe) version:
Current Raku implementations do not yet support the -i flag for editing files in place, so we roll our own (rather unsafe) version:


<lang perl6>slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_)
<syntaxhighlight lang="raku" line>slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_)
for <a.txt b.txt c.txt>;</lang>
for <a.txt b.txt c.txt>;</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>>> f: request-file
<syntaxhighlight lang="red">>> f: request-file
>> str: read f
>> str: read f
>> replace/all str "Goodbye London!" "Hello New York!"
>> replace/all str "Goodbye London!" "Hello New York!"
>> write f str</lang>
>> write f str</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,258: Line 1,258:
This example works under "DOS" and/or "DOS" under Microsoft Windows.
This example works under "DOS" and/or "DOS" under Microsoft Windows.
<br><br>File names that contain blanks should have their blanks replaced with commas.
<br><br>File names that contain blanks should have their blanks replaced with commas.
<lang rexx>/*REXX program reads the files specified and globally replaces a string. */
<syntaxhighlight lang="rexx">/*REXX program reads the files specified and globally replaces a string. */
old= "Goodbye London!" /*the old text to be replaced. */
old= "Goodbye London!" /*the old text to be replaced. */
new= "Hello New York!" /* " new " used for replacement. */
new= "Hello New York!" /* " new " used for replacement. */
Line 1,284: Line 1,284:


say '──────── file was changed: ' fn " with" changes 'lines changed.'
say '──────── file was changed: ' fn " with" changes 'lines changed.'
end /*f*/ /*stick a fork in it, we're all done. */</lang>
end /*f*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
<br><br>
Line 1,303: Line 1,303:
===Version 2===
===Version 2===
considering file ids that contain blanks
considering file ids that contain blanks
<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* Copy all files *.txt to *.rpl
* Copy all files *.txt to *.rpl
* replacing all occurrences of old by new
* replacing all occurrences of old by new
Line 1,394: Line 1,394:
ol=ol||s
ol=ol||s
End
End
Return ol</lang>
Return ol</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 1,418: Line 1,418:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
filenames = ["ReadMe.txt", "ReadMe2.txt"]
filenames = ["ReadMe.txt", "ReadMe2.txt"]


Line 1,439: Line 1,439:
fseek(fp,0,C_FILESTART)
fseek(fp,0,C_FILESTART)
return nFileSize
return nFileSize
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 1,448: Line 1,448:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>file$(1) ="data1.txt"
<syntaxhighlight lang="runbasic">file$(1) ="data1.txt"
file$(2) ="data2.txt"
file$(2) ="data2.txt"
file$(3) ="data3.txt"
file$(3) ="data3.txt"
Line 1,480: Line 1,480:
i = i + 1
i = i + 1
WEND
WEND
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
//! Author: Rahul Sharma
//! Author: Rahul Sharma
//! Github: <https://github.com/creativcoder>
//! Github: <https://github.com/creativcoder>
Line 1,530: Line 1,530:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,536: Line 1,536:


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>import java.io.{File, PrintWriter}
<syntaxhighlight lang="scala">import java.io.{File, PrintWriter}


object GloballyReplaceText extends App {
object GloballyReplaceText extends App {
Line 1,548: Line 1,548:
}
}


}</lang>
}</syntaxhighlight>


=={{header|Sed}}==
=={{header|Sed}}==
{{works with|GNU Sed}}
{{works with|GNU Sed}}
<lang bash>sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt</lang>
<syntaxhighlight lang="bash">sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "getf.s7i";
include "getf.s7i";
Line 1,568: Line 1,568:
putf(fileName, content);
putf(fileName, content);
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var names = %w(
<syntaxhighlight lang="ruby">var names = %w(
a.txt
a.txt
b.txt
b.txt
Line 1,581: Line 1,581:
line.gsub("Goodbye London!", "Hello New York!")
line.gsub("Goodbye London!", "Hello New York!")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|fileutil}}
{{tcllib|fileutil}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require fileutil
package require fileutil


Line 1,599: Line 1,599:
foreach filename $fileList {
foreach filename $fileList {
fileutil::updateInPlace $filename $replacementCmd
fileutil::updateInPlace $filename $replacementCmd
}</lang>
}</syntaxhighlight>




=={{header|Transd}}==
=={{header|Transd}}==
<lang scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd


MainModule: {
MainModule: {
Line 1,616: Line 1,616:
(write fs (to-bytes s) (size s)))))
(write fs (to-bytes s) (size s)))))
)
)
}</lang>
}</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
files="a.txt'b.txt'c.txt"
files="a.txt'b.txt'c.txt"
Line 1,641: Line 1,641:
ENDLOOP
ENDLOOP
ERROR/STOP DELETE ("scratch")
ERROR/STOP DELETE ("scratch")
</syntaxhighlight>
</lang>


=={{header|TXR}}==
=={{header|TXR}}==
Line 1,647: Line 1,647:
===Extraction Language===
===Extraction Language===


<lang txr>@(next :args)
<syntaxhighlight lang="txr">@(next :args)
@(repeat)
@(repeat)
@file
@file
Line 1,657: Line 1,657:
@(end)
@(end)
@(do @(rename-path `@file.tmp` file))
@(do @(rename-path `@file.tmp` file))
@(end)</lang>
@(end)</syntaxhighlight>
Run:
Run:
<pre>$ cat foo.txt
<pre>$ cat foo.txt
Line 1,683: Line 1,683:
===TXR Lisp===
===TXR Lisp===


<lang txrlisp>(each ((fname *args*))
<syntaxhighlight lang="txrlisp">(each ((fname *args*))
(let* ((infile (open-file fname))
(let* ((infile (open-file fname))
(outfile (open-file `@fname.tmp` "w"))
(outfile (open-file `@fname.tmp` "w"))
Line 1,689: Line 1,689:
(edited (regsub #/Goodbye, London/ "Hello, New York" content)))
(edited (regsub #/Goodbye, London/ "Hello, New York" content)))
(put-string edited outfile)
(put-string edited outfile)
(rename-path `@fname.tmp` fname)))</lang>
(rename-path `@fname.tmp` fname)))</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash}}
{{works with|bash}}
<lang bash>replace() {
<syntaxhighlight lang="bash">replace() {
local search=$1 replace=$2
local search=$1 replace=$2
local file lines line
local file lines line
Line 1,705: Line 1,705:
done
done
}
}
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt</lang>
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt</syntaxhighlight>


{{works with|ksh93}}
{{works with|ksh93}}
<lang bash>function replace {
<syntaxhighlight lang="bash">function replace {
typeset search=$1 replace=$2
typeset search=$1 replace=$2
typeset file lines line
typeset file lines line
Line 1,720: Line 1,720:
done
done
}
}
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt</lang>
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
<lang VBScript>
Const ForReading = 1
Const ForReading = 1
Const ForWriting = 2
Const ForWriting = 2
Line 1,739: Line 1,739:
Next
Next
End With
End With
</syntaxhighlight>
</lang>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
The list of files is in file "files.lst" which is expected to be in current directory.
The list of files is in file "files.lst" which is expected to be in current directory.
<lang vedit>File_Open("files.lst") // list of files to process
<syntaxhighlight lang="vedit">File_Open("files.lst") // list of files to process
#20 = Reg_Free // text register for filename
#20 = Reg_Free // text register for filename


Line 1,755: Line 1,755:


Reg_Empty(#20) // Cleanup
Reg_Empty(#20) // Cleanup
Buf_Quit(OK)</lang>
Buf_Quit(OK)</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File


var files = ["file1.txt", "file2.txt"]
var files = ["file1.txt", "file2.txt"]
Line 1,769: Line 1,769:
}
}
System.print("%(file) now contains: %(File.read(file))")
System.print("%(file) now contains: %(File.read(file))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,783: Line 1,783:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
string 0; \use zero-terminated strings


Line 1,841: Line 1,841:
[File:= ["Alpha.txt", "Beta.txt", "Gamma.txt", "Delta.txt"];
[File:= ["Alpha.txt", "Beta.txt", "Gamma.txt", "Delta.txt"];
for I:= 0 to 4-1 do ReplaceText(File(I));
for I:= 0 to 4-1 do ReplaceText(File(I));
]</lang>
]</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn sed(data,src,dst){
<syntaxhighlight lang="zkl">fcn sed(data,src,dst){
srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data);
srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data);
n:=0; while(Void!=(n:=data.find(src,n)))
n:=0; while(Void!=(n:=data.find(src,n)))
Line 1,854: Line 1,854:
if(sed(data,"Goodbye London!", "Hello New York!"))
if(sed(data,"Goodbye London!", "Hello New York!"))
{ f:=File(fname,"w"); f.write(data); f.close(); }
{ f:=File(fname,"w"); f.write(data); f.close(); }
}</lang>
}</syntaxhighlight>
This is a read file/blast it/write if changed. You could also do it line by line.
This is a read file/blast it/write if changed. You could also do it line by line.
<lang zkl>vm.arglist.apply2(sedFile);
<syntaxhighlight lang="zkl">vm.arglist.apply2(sedFile);
$ zkl bbb foo.txt bar.txt</lang>
$ zkl bbb foo.txt bar.txt</syntaxhighlight>
The apply2 method doesn't return anything, it is a side effects method.
The apply2 method doesn't return anything, it is a side effects method.
You could also easily thread this (by using sedFile.launch or sedFile.strand depending on if you wanted a true thread or a co-op thread). I didn't because I didn't want to bother with checking for duplicate files or file locking.
You could also easily thread this (by using sedFile.launch or sedFile.strand depending on if you wanted a true thread or a co-op thread). I didn't because I didn't want to bother with checking for duplicate files or file locking.