Globally replace text in several files: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(→‎{{header|Haskell}}: Simplifed type of recursion in replace, preferred guards to if then else, applied Hlint)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(10 intermediate revisions by 7 users not shown)
Line 9:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">L(fname) fs:list_dir(‘.’)
I fname.ends_with(‘.txt’)
V fcontents = File(fname).read()
File(fname, ‘w’).write(fcontents.replace(‘Goodbye London!’, ‘Hello, New York!’))
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line, Ada.Directories;
 
procedure Global_Replace is
Line 76:
File_Replace(Ada.Command_Line.Argument(I), Pattern, Replacement);
end loop;
end Global_Replace;</langsyntaxhighlight>
 
Ouput:
Line 96:
"Hello New York!"
"Byebye London!" "Byebye London!" "Byebye London!" </pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">files: select list "." 'f -> suffix? ".txtfile"
 
loop files 'file ->
write file replace read file "Goodbye London!" "Hello New York!"</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="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
loop, Parse, listFiles, |
Line 108 ⟶ 114:
fileAppend, %contents%, %A_LoopField% ; Re-create the file with new contents
}
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GLOBALLY_REPLACE_TEXT_IN_SEVERAL_FILES.AWK filename(s)
BEGIN {
Line 140 ⟶ 146:
exit(0)
}
</syntaxhighlight>
</lang>
 
{{works with|gawk}}
<langsyntaxhighlight lang="awk">@include "readfile"
BEGIN {
while(++i < ARGC)
print gensub("Goodbye London!","Hello New York!","g", readfile(ARGV[i])) > ARGV[i]
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 154 ⟶ 160:
Pass the files on the command line (i.e. <code>global-replace *.txt</code>).
 
<langsyntaxhighlight lang="qbasic">CONST matchtext = "Goodbye London!"
CONST repltext = "Hello New York!"
CONST matchlen = LEN(matchtext)
Line 191 ⟶ 197:
WEND
L0 += 1
WEND</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> FindThis$ = "Goodbye London!"
ReplaceWith$ = "Hello New York!"
Line 224 ⟶ 230:
OSCLI "REN """ + tmpfile$ + """ """ + infile$ + """"
NEXT
END</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
Line 301 ⟶ 307:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">
using System.Collections.Generic;
using System.IO;
Line 319 ⟶ 325:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
#include <iterator>
#include <boost/regex.hpp>
Line 348 ⟶ 354:
}
return 0 ;
}</langsyntaxhighlight>
 
Modern C++ version:
<langsyntaxhighlight lang="cpp">#include <regex>
#include <fstream>
 
Line 369 ⟶ 375:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn hello-goodbye [& more]
(doseq [file more]
(spit file (.replace (slurp file) "Goodbye London!" "Hello New York!"))))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
<lang Lisp>
(defun hello-goodbye (files)
(labels ((replace-from-file (file)
Line 394 ⟶ 400:
(write-lines-to-file (replace-from-file file) file)))
(map nil #'replace-in-file files)))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{works with|D|2}}
<langsyntaxhighlight lang="d">import std.file, std.array;
 
void main() {
Line 405 ⟶ 411:
write(fn, replace(cast(string)read(fn), from, to));
}
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IoUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Globally_replace_text_in_several_files;
 
Line 439 ⟶ 445:
begin
StringReplaceByFile('Goodbye London!', 'Hello New York!', ['a.txt', 'b.txt', 'c.txt']);
end.</langsyntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( globally_replace_text ).
 
Line 465 ⟶ 471:
io:fwrite( "Error: Could not write ~p: ~p~n", [File, Error] ),
error.
</syntaxhighlight>
</lang>
 
{{out}}
Line 491 ⟶ 497:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System.IO
 
[<EntryPoint>]
Line 502 ⟶ 508:
if content <> newContent then
File.WriteAllText(name, newContent)
0</langsyntaxhighlight>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2019-10-06}}
<langsyntaxhighlight lang="factor">USING: fry io.encodings.utf8 io.files kernel qw sequences
splitting ;
 
Line 517 ⟶ 523:
 
qw{ a.txt b.txt c.txt }
"Goodbye London!" "Hello New York!" global-replace</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 526 ⟶ 532:
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.<langsyntaxhighlight Fortranlang="fortran"> SUBROUTINE FILEHACK(FNAME,THIS,THAT) !Attacks a file!
CHARACTER*(*) FNAME !The name of the file, presumed to contain text.
CHARACTER*(*) THIS !The text sought in each record.
Line 590 ⟶ 596:
END DO !On to the next.
 
END</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|BASIC}}
<syntaxhighlight lang="freebasic">Const matchtext = "Goodbye London!"
Const repltext = "Hello New York!"
Const matchlen = Len(matchtext)
 
Dim As Integer x, L0 = 1
dim as string filespec, linein
 
L0 = 1
While Len(Command(L0))
filespec = Dir(Command(L0))
While Len(filespec)
Open filespec For Binary As 1
linein = Space(Lof(1))
Get #1, 1, linein
Do
x = Instr(linein, matchtext)
If x Then
linein = Left(linein, x - 1) & repltext & Mid(linein, x + matchlen)
Else
Exit Do
End If
Loop
Close
Open filespec For Output As 1
Print #1, linein;
Close
filespec = Dir
Wend
L0 += 1
Wend</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn GloballyCreateAndReplaceFileText
NSUInteger i
CFURLRef url
CFMutableArrayRef mutURL = fn MutableArrayNew
CFArrayRef fileNames = @[@"file1", @"file2", @"file3"]
CFStringRef fileContentStr
CFStringRef originalText = @"Goodbye London!"
CFStringRef replacementText = @"Hello New York!"
for i = 0 to len(fileNames) - 1
CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
url = fn URLByAppendingPathComponent( desktopURL, fileNames[i] )
url = fn URLByAppendingPathExtension( url, @"txt" )
CFStringRef fullText = fn StringWithFormat( @"%@ What an interesting city.", originalText )
fn StringWriteToURL( fullText, url, YES, NSUTF8StringEncoding, NULL )
MutableArrayAddObject( mutURL, url )
next
NSLog( @"Original text:" )
for i = 0 to len(mutURL) - 1
fileContentStr = fn StringWithContentsOfURL( mutURL[i], NSUTF8StringEncoding, NULL )
NSLog( @"Contents at: %@ = %@", fn URLPath( mutURL[i] ), fileContentStr )
CFStringRef modifiedText = fn StringByReplacingOccurrencesOfString( fileContentStr, originalText, replacementText )
fn StringWriteToURL( modifiedText, mutURL[i], YES, NSUTF8StringEncoding, NULL )
next
NSLog( @"\nReplacement text:" )
for i = 0 to len(mutURL) - 1
fileContentStr = fn StringWithContentsOfURL( mutURL[i], NSUTF8StringEncoding, NULL )
NSLog( @"Contents at: %@ = %@", fn URLPath( mutURL[i] ), fileContentStr )
next
end fn
 
fn GloballyCreateAndReplaceFileText
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Original text:
Contents at: /Users/ken/Desktop/file1.txt = Goodbye London! What an interesting city.
Contents at: /Users/ken/Desktop/file2.txt = Goodbye London! What an interesting city.
Contents at: /Users/ken/Desktop/file3.txt = Goodbye London! What an interesting city.
 
Replacement text:
Contents at: /Users/ken/Desktop/file1.txt = Hello New York! What an interesting city.
Contents at: /Users/ken/Desktop/file2.txt = Hello New York! What an interesting city.
Contents at: /Users/ken/Desktop/file3.txt = Hello New York! What an interesting city.
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 643 ⟶ 735:
_, err = f.WriteAt(r, 0)
return
}</langsyntaxhighlight>
 
=={{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).
This code doesn't rewrite the files, it just returns the changes made to the contents of the files.
<langsyntaxhighlight Haskelllang="haskell">import Data.List (tails, elemIndices, isPrefixOf)
 
replace :: String -> String -> String -> String
Line 669 ⟶ 761:
f <- mapM readFile files
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).
<langsyntaxhighlight Haskelllang="haskell">replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace a b = go
where
w = length a
go [] = []
go xxxxs@(x : xs)
| a `isPrefixOf` xxxxs = b <> go (drop (length a)w xxxxs)
| otherwise = x : go xs</langsyntaxhighlight>
 
and with different library imports, we could also write things like:
<syntaxhighlight lang="haskell">import Data.List (intercalate)
import Data.List.Split (splitOn)
 
replace :: String -> String -> String -> String
replace a b = intercalate b . splitOn a</syntaxhighlight>
 
 
'''Example:'''
<pre>
Line 692 ⟶ 794:
=={{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.
<langsyntaxhighlight Iconlang="icon">procedure main()
globalrepl("Goodbye London","Hello New York","a.txt","b.txt") # variable args for files
end
Line 706 ⟶ 808:
end
 
link strings # for replace</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 715 ⟶ 817:
If <code>files</code> is a variable with the desired list of file names:
 
<langsyntaxhighlight lang="j">require'strings'
(1!:2~rplc&('Goodbye London!';'Hello New York!')@(1!:1))"0 files</langsyntaxhighlight>
 
=={{header|Java}}==
Minimalistic version, assumes default encoding.
{{works with|Java|7}}
<langsyntaxhighlight lang="java">import java.io.*;
import java.nio.file.*;
 
Line 736 ⟶ 838:
}
}
}</langsyntaxhighlight>
 
In Java 11 the body could be shortened to:
<langsyntaxhighlight lang="java">
for (String fn : List.of("file1.txt","file2.txt")) {
Path path = Path.of(fn);
Line 745 ⟶ 847:
Files.readString(path).replace("Goodbye London!", "Hello New York!"));
}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
{{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".
<langsyntaxhighlight lang="bash">for file
do
jq -Rr 'gsub($from; $to)' --arg from 'Goodbye London!' --arg to 'Hello New York!' "$file" |
sponge "$file"
done</langsyntaxhighlight>
 
The jq filter used above is `gsub/2`, which however is designed for regular expressions. Here is a string-oriented alternative:
<langsyntaxhighlight lang="jq">def gsubst($from; $to):
($from | length) as $len
| def g:
index($from) as $ix
| if $ix then .[:$ix] + $to + (.[($ix+$len):] | g) else . end;
g;</langsyntaxhighlight>
 
=={{header|Jsish}}==
'''For the demo, the code does not overwrite the samples, but creates a .new file.'''
<langsyntaxhighlight lang="javascript">/* Global replace in Jsish */
if (console.args.length == 0) {
console.args.push('-');
Line 787 ⟶ 889:
}
} catch(err) { puts(err, 'processing', fn); }
}</langsyntaxhighlight>
 
To meet the task specification, change
 
<langsyntaxhighlight lang="javascript">if (fn == 'stdin') fn = 'stdout'; else fn += '.new';</langsyntaxhighlight>
 
to
 
<langsyntaxhighlight lang="javascript">if (fn == 'stdin') fn = 'stdout';</langsyntaxhighlight>
 
removing the else clause. The code will then overwrite originals.
Line 812 ⟶ 914:
=={{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).
<langsyntaxhighlight lang="julia">filenames = ["f1.txt", "f2.txt"]
for filename in filenames
txt = read(filename, String)
Line 818 ⟶ 920:
write(f, replace(txt, "Goodbye London!" => "Hello New York!"))
end
end</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.io.File
Line 835 ⟶ 937:
println(f.readText())
}
}</langsyntaxhighlight>
 
{{out}}
Line 849 ⟶ 951:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
local(files = array('f1.txt', 'f2.txt'))
Line 862 ⟶ 964:
#file -> writebytes(#content)
}
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
nomainwin
 
Line 902 ⟶ 1,004:
end if
end function
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">filenames = { "f1.txt", "f2.txt" }
 
for _, fn in pairs( filenames ) do
Line 916 ⟶ 1,018:
fp:write( str )
fp:close()
end</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">listOfFiles = {"a.txt", "b.txt", "c.txt"};
Do[
filename = listOfFiles[[i]];
Line 925 ⟶ 1,027:
filetext = StringReplace[filetext, "Goodbye London!" -> "Hello New York!"];
Export[filename, filetext, "Text"]
, {i, 1, Length[listOfFiles]}]</langsyntaxhighlight>
File b.txt before the code is run:
<pre>second file for the Globally replace text in several files problem.
Line 942 ⟶ 1,044:
=={{header|newLISP}}==
{{works with|newLisp|10.7.5}}
<syntaxhighlight lang="newlisp">
<lang newLISP>
(define (replace-in-file filename this bythat)
(set 'content (read-file filename))
Line 957 ⟶ 1,059:
 
(exit)
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
let fr = "Goodbye London!"
Line 966 ⟶ 1,068:
 
for fn in ["a.txt", "b.txt", "c.txt"]:
fn.writeFile fn.readFile.replace(fr, to)</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class ReplaceAll {
function : Main(args : String[]) ~ Nil {
files := ["text1.txt", "text2.txt"];
Line 978 ⟶ 1,080:
};
}
}</langsyntaxhighlight>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">FUNCTION replaceText RETURNS LOGICAL (
i_cfile_list AS CHAR,
i_cfrom AS CHAR,
Line 1,002 ⟶ 1,104:
"Goodbye London!",
"Hello New York!"
).</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">Program StringReplace;
 
uses
Line 1,030 ⟶ 1,132:
AllText.Destroy;
end;
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="bash">perl -pi -e "s/Goodbye London\!/Hello New York\!/g;" a.txt b.txt c.txt</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,039 ⟶ 1,141:
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.
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>procedure global_replace(string s, string r, sequence file_list)
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o</span>
for i=1 to length(file_list) do
<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>
string filename = file_list[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">file_list</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer fn = open(filename,"rb")
<span style="color: #004080;">string</span> <span style="color: #000000;">filename</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">file_list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
if fn=-1 then ?9/0 end if -- message/retry?
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"rb"</span><span style="color: #0000FF;">)</span>
string text = get_text(fn)
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- message/retry?</span>
close(fn)
<span style="color: #004080;">string</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
text = substitute(text,s,r)
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
fn = open(filename,"wb")
<span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
puts(fn,text)
<span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"wb"</span><span style="color: #0000FF;">)</span>
close(fn)
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
sequence file_list = {"ctrace.out"}
global_replace("Goodbye London!", "Hello New York!", file_list)</lang>
<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>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(for File '(a.txt b.txt c.txt)
(call 'mv File (tmp File))
(out File
(in (tmp File)
(while (echo "Goodbye London!")
(prin "Hello New York!") ) ) ) )</langsyntaxhighlight>
 
=={{header|PowerBASIC}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="powerbasic">$matchtext = "Goodbye London!"
$repltext = "Hello New York!"
 
Line 1,088 ⟶ 1,193:
INCR L0
WEND
END FUNCTION</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$listfiles = @('file1.txt','file2.txt')
$old = 'Goodbye London!'
Line 1,098 ⟶ 1,203:
(Get-Content $file).Replace($old,$new) | Set-Content $file
}
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure GRTISF(List File$(), Find$, Replace$)
Protected Line$, Out$, OutFile$, i
ForEach File$()
Line 1,132 ⟶ 1,237:
EndIf
Next
EndProcedure</langsyntaxhighlight>
Implementation
<pre>NewList Xyz$()
Line 1,144 ⟶ 1,249:
From [http://docs.python.org/library/fileinput.html Python docs]. (Note: in-place editing does not work for MS-DOS 8+3 filesystems.).
 
<langsyntaxhighlight lang="python">import fileinput
 
for line in fileinput.input(inplace=True):
print(line.replace('Goodbye London!', 'Hello New York!'), end='')
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Code wrapped in a convenient script:
<langsyntaxhighlight lang="racket">
#!/usr/bin/env racket
#lang racket
Line 1,176 ⟶ 1,281:
(begin (display-to-file text2 file #:exists 'replace)
(printf " modified copy saved in place\n")))))
</syntaxhighlight>
</lang>
Sample run:
<pre>
Line 1,199 ⟶ 1,304:
Current Raku implementations do not yet support the -i flag for editing files in place, so we roll our own (rather unsafe) version:
 
<syntaxhighlight lang="raku" perl6line>slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_)
for <a.txt b.txt c.txt>;</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">>> f: request-file
>> str: read f
>> replace/all str "Goodbye London!" "Hello New York!"
>> write f str</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,212 ⟶ 1,317:
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.
<langsyntaxhighlight lang="rexx">/*REXX program reads the files specified and globally replaces a string. */
old= "Goodbye London!" /*the old text to be replaced. */
new= "Hello New York!" /* " new " used for replacement. */
Line 1,238 ⟶ 1,343:
 
say '──────── file was changed: ' fn " with" changes 'lines changed.'
end /*f*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
Line 1,257 ⟶ 1,362:
===Version 2===
considering file ids that contain blanks
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Copy all files *.txt to *.rpl
* replacing all occurrences of old by new
Line 1,348 ⟶ 1,453:
ol=ol||s
End
Return ol</langsyntaxhighlight>
Sample output:
<pre>
Line 1,372 ⟶ 1,477:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
filenames = ["ReadMe.txt", "ReadMe2.txt"]
 
Line 1,393 ⟶ 1,498:
fseek(fp,0,C_FILESTART)
return nFileSize
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Line 1,402 ⟶ 1,507:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">file$(1) ="data1.txt"
file$(2) ="data2.txt"
file$(3) ="data3.txt"
Line 1,434 ⟶ 1,539:
i = i + 1
WEND
END FUNCTION</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
//! Author: Rahul Sharma
//! Github: <https://github.com/creativcoder>
Line 1,484 ⟶ 1,589:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,490 ⟶ 1,595:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.io.{File, PrintWriter}
 
object GloballyReplaceText extends App {
Line 1,502 ⟶ 1,607:
}
 
}</langsyntaxhighlight>
 
=={{header|Sed}}==
{{works with|GNU Sed}}
<langsyntaxhighlight lang="bash">sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "getf.s7i";
Line 1,522 ⟶ 1,627:
putf(fileName, content);
end for;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var names = %w(
a.txt
b.txt
Line 1,535 ⟶ 1,640:
line.gsub("Goodbye London!", "Hello New York!")
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{tcllib|fileutil}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require fileutil
 
Line 1,553 ⟶ 1,658:
foreach filename $fileList {
fileutil::updateInPlace $filename $replacementCmd
}</langsyntaxhighlight>
 
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule: {
_start: (λ
(with files ["a.txt" "b.txt" "c.txt"] fs FileStream()
(for f in files do
(open-r fs f)
(with s (replace (read-text fs)
"Goodbye London!" "Hello New York!")
(close fs)
(open-w fs f)
(write fs (to-bytes s) (size s)))))
)
}</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
files="a.txt'b.txt'c.txt"
Line 1,578 ⟶ 1,700:
ENDLOOP
ERROR/STOP DELETE ("scratch")
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
Line 1,584 ⟶ 1,706:
===Extraction Language===
 
<langsyntaxhighlight lang="txr">@(next :args)
@(repeat)
@file
Line 1,594 ⟶ 1,716:
@(end)
@(do @(rename-path `@file.tmp` file))
@(end)</langsyntaxhighlight>
Run:
<pre>$ cat foo.txt
Line 1,620 ⟶ 1,742:
===TXR Lisp===
 
<langsyntaxhighlight lang="txrlisp">(each ((fname *args*))
(let* ((infile (open-file fname))
(outfile (open-file `@fname.tmp` "w"))
Line 1,626 ⟶ 1,748:
(edited (regsub #/Goodbye, London/ "Hello, New York" content)))
(put-string edited outfile)
(rename-path `@fname.tmp` fname)))</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
<langsyntaxhighlight lang="bash">replace() {
local search=$1 replace=$2
local file lines line
Line 1,642 ⟶ 1,764:
done
}
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt</langsyntaxhighlight>
 
{{works with|ksh93}}
<langsyntaxhighlight lang="bash">function replace {
typeset search=$1 replace=$2
typeset file lines line
Line 1,657 ⟶ 1,779:
done
}
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt</langsyntaxhighlight>
 
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
<lang VBScript>
Const ForReading = 1
Const ForWriting = 2
Line 1,676 ⟶ 1,798:
Next
End With
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
The list of files is in file "files.lst" which is expected to be in current directory.
<langsyntaxhighlight lang="vedit">File_Open("files.lst") // list of files to process
#20 = Reg_Free // text register for filename
 
Line 1,692 ⟶ 1,814:
 
Reg_Empty(#20) // Cleanup
Buf_Quit(OK)</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
 
var files = ["file1.txt", "file2.txt"]
Line 1,706 ⟶ 1,828:
}
System.print("%(file) now contains: %(File.read(file))")
}</langsyntaxhighlight>
 
{{out}}
Line 1,720 ⟶ 1,842:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
 
Line 1,778 ⟶ 1,900:
[File:= ["Alpha.txt", "Beta.txt", "Gamma.txt", "Delta.txt"];
for I:= 0 to 4-1 do ReplaceText(File(I));
]</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn sed(data,src,dst){
srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data);
n:=0; while(Void!=(n:=data.find(src,n)))
Line 1,791 ⟶ 1,913:
if(sed(data,"Goodbye London!", "Hello New York!"))
{ f:=File(fname,"w"); f.write(data); f.close(); }
}</langsyntaxhighlight>
This is a read file/blast it/write if changed. You could also do it line by line.
<langsyntaxhighlight lang="zkl">vm.arglist.apply2(sedFile);
$ zkl bbb foo.txt bar.txt</langsyntaxhighlight>
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.
9,476

edits