WolframLang: Find/Replace Script
Here's a sample code to do find replace multiple pairs of strings in all files in a dir.
(* Find and replace strings in a dir. http://xahlee.info/M/wolframlang_find_replace.html Version 2022-01-06 2022-01-12 2022-05-08 *) inputDir = "c:/Users/xah/xx/"; makeBackUp = True; dirDepth = Infinity; fileNameExtension = "*html"; findReplacePairs = { "accesskey" -> "accesskeysb9mD", "describes" -> "describesGgRYn" }; nowDate = DateString[Now, {"ISODate", "_", "HourExact"}]; processFile = Function[{filePath}, Module[{content = ReadString[filePath]}, If[makeBackUp, CopyFile[filePath, StringJoin[filePath, "~", nowDate, "~"], OverwriteTarget -> True]]; WriteString[filePath, StringReplace[content, findReplacePairs]]]]; Scan[ processFile, FileNames[fileNameExtension, inputDir, dirDepth] ] Print[ "done." ]
- Copy and paste into a file and save it as
find_replace.wls
- Modify the inputDir, and find replace string pairs.
- In terminal, run
wolframscript -file find_replace.wls
You can also copy and paste it into a Wolfram Notebook .
[see WolframScript Tutorial]
WARNING and bugs
- 2022-01-12 if you run this twice in notebook, the file doubles size. Unless you quit the kernel each time. Seems a cache issue. am unable to find out how to clear it. shouldn't need to.
- 2022-01-12 if the file has unix style line ending, and the WolframScript is run in Microsoft Windows, running it twice adds incorrect line ending.
- 2022-01-12 WARNING: if the file contains unicode and is in utf8 encoding, the result will have incorrect characters.
Am not sure its a bug, or the script needs to be refined on file encoding and line ending convention. Maybe both.
xtodoFind Replace Scripts
- Golang: Find String (grep) Script
- Golang: Script to Find Replace Multi-Pairs of Regex in a Directory
- Python: Script to Find Replace Multi-Pairs Regex in a Directory
- Perl: Find Replace String Pairs in Directory
- Emacs: Interactive Find Replace Text in Directory
- Emacs: Find Replace in Pure Elisp, xah-find.el
- WolframLang: Find/Replace Script