Globally replace text in several files: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 9: | Line 9: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<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}}== |
||
< |
<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;</ |
end Global_Replace;</syntaxhighlight> |
||
Ouput: |
Ouput: |
||
Line 98: | Line 98: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<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}} |
||
< |
<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] |
||
}</ |
}</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>). |
||
< |
<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</ |
WEND</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<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</ |
END</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<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; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<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++}}== |
||
< |
<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 ; |
||
}</ |
}</syntaxhighlight> |
||
Modern C++ version: |
Modern C++ version: |
||
< |
<syntaxhighlight lang="cpp">#include <regex> |
||
#include <fstream> |
#include <fstream> |
||
Line 369: | Line 369: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(defn hello-goodbye [& more] |
||
(doseq [file more] |
(doseq [file more] |
||
(spit file (.replace (slurp file) "Goodbye London!" "Hello New York!"))))</ |
(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}} |
||
< |
<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)); |
||
} |
} |
||
}</ |
}</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.</ |
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#}}== |
||
< |
<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</ |
0</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
{{works with|Factor|0.99 2019-10-06}} |
{{works with|Factor|0.99 2019-10-06}} |
||
< |
<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</ |
"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.< |
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</ |
END</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
{{trans|BASIC}} |
{{trans|BASIC}} |
||
< |
<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</ |
Wend</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 676: | Line 676: | ||
_, err = f.WriteAt(r, 0) |
_, err = f.WriteAt(r, 0) |
||
return |
return |
||
}</ |
}</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. |
||
< |
<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). |
||
< |
<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</ |
| 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: |
||
< |
<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</ |
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. |
||
< |
<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</ |
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: |
||
< |
<syntaxhighlight lang="j">require'strings' |
||
(1!:2~rplc&('Goodbye London!';'Hello New York!')@(1!:1))"0 files</ |
(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}} |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
import java.nio.file.*; |
import java.nio.file.*; |
||
Line 779: | Line 779: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
In Java 11 the body could be shortened to: |
In Java 11 the body could be shortened to: |
||
< |
<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". |
||
< |
<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</ |
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: |
||
< |
<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;</ |
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.''' |
||
< |
<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); } |
||
}</ |
}</syntaxhighlight> |
||
To meet the task specification, change |
To meet the task specification, change |
||
< |
<syntaxhighlight lang="javascript">if (fn == 'stdin') fn = 'stdout'; else fn += '.new';</syntaxhighlight> |
||
to |
to |
||
< |
<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). |
||
< |
<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</ |
end</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<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()) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 892: | Line 892: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<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) |
||
} |
} |
||
}</ |
}</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}}== |
||
< |
<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</ |
end</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<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]}]</ |
, {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}}== |
||
< |
<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)</ |
fn.writeFile fn.readFile.replace(fr, to)</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<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: | ||
}; |
}; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
< |
<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!" |
||
).</ |
).</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{works with|Free_Pascal}} |
{{works with|Free_Pascal}} |
||
< |
<syntaxhighlight lang="pascal">Program StringReplace; |
||
uses |
uses |
||
Line 1,073: | Line 1,073: | ||
AllText.Destroy; |
AllText.Destroy; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<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. |
||
<!--< |
<!--<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<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!") ) ) ) )</ |
(prin "Hello New York!") ) ) ) )</syntaxhighlight> |
||
=={{header|PowerBASIC}}== |
=={{header|PowerBASIC}}== |
||
{{trans|BASIC}} |
{{trans|BASIC}} |
||
< |
<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</ |
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}}== |
||
< |
<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</ |
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.). |
||
< |
<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: |
||
< |
<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 |
<syntaxhighlight lang="raku" line>slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_) |
||
for <a.txt b.txt c.txt>;</ |
for <a.txt b.txt c.txt>;</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<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</ |
>> 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. |
||
< |
<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. */</ |
end /*f*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]]. |
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[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 |
||
< |
<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</ |
Return ol</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 1,418: | Line 1,418: | ||
=={{header|Ring}}== |
=={{header|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}}== |
||
< |
<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</ |
END FUNCTION</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|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}}== |
||
< |
<syntaxhighlight lang="scala">import java.io.{File, PrintWriter} |
||
object GloballyReplaceText extends App { |
object GloballyReplaceText extends App { |
||
Line 1,548: | Line 1,548: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sed}}== |
=={{header|Sed}}== |
||
{{works with|GNU Sed}} |
{{works with|GNU Sed}} |
||
< |
<syntaxhighlight lang="bash">sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<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;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<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!") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{tcllib|fileutil}} |
{{tcllib|fileutil}} |
||
< |
<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 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Transd}}== |
=={{header|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))))) |
||
) |
) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|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=== |
||
< |
<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)</ |
@(end)</syntaxhighlight> |
||
Run: |
Run: |
||
<pre>$ cat foo.txt |
<pre>$ cat foo.txt |
||
Line 1,683: | Line 1,683: | ||
===TXR Lisp=== |
===TXR Lisp=== |
||
< |
<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)))</ |
(rename-path `@fname.tmp` fname)))</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<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</ |
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt</syntaxhighlight> |
||
{{works with|ksh93}} |
{{works with|ksh93}} |
||
< |
<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</ |
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. |
||
< |
<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)</ |
Buf_Quit(OK)</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<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))") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,783: | Line 1,783: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<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)); |
||
]</ |
]</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<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(); } |
||
}</ |
}</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. |
||
< |
<syntaxhighlight lang="zkl">vm.arglist.apply2(sedFile); |
||
$ zkl bbb foo.txt bar.txt</ |
$ 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. |