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 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 Tutorial〕
🛑 WARNING: Bug
this 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.
xtodoFind Replace Scripts
- Golang: Find String (grep) Script
- Golang: Script to Find Replace Multi-Pairs of Regex in a Directory
- Python: Find Replace Regex in Dir
- Perl: Find Replace String Pairs in Directory
- Emacs: Interactive Find Replace Text in Directory
- Emacs: Xah Find Replace (xah-find.el)
- WolframLang: Find/Replace Script
WolframLang, Shell Tasks
- WolframScript Tutorial
- WolframLang: File Name Extension
- WolframLang: Shell Tasks
- WolframLang: Navigate Directory
- WolframLang: List Files (Walk Directory)
- WolframLang: File Path Functions
- WolframLang: Delete Dir
- WolframLang: is File or Dir
- WolframLang: File Exist
- WolframLang: Get File Date
- WolframLang: Get File Size
- WolframLang: Print File Content
- WolframLang: Get File Hash
- WolframLang: Read File
- WolframLang: Write File
- WolframLang: Load a Package or File
- WolframLang: Get Environment Variable
- WolframLang: Date Time
- WolframLang: Find/Replace Script