Wolfram: Find Replace Text 📜
Here's a sample code to do find replace multiple pairs of strings in all files in a dir.
(* Find and replace multiple pairs of strings for all files a dir. file name: find_replace.wls URL: http://xahlee.info/M/wolframlang_find_replace.html Version: 2022-01-06 2023-12-04 *) 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]]; Close[ filePath ] ]]; 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]
🛑 warning: Bug
xtodothis is with Mathematica version 12.x and 13.2, as of 2023-10-21
- if the file has unix style line ending, and the WolframScript is run in Microsoft Windows, running it twice adds incorrect line ending.
- 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.