WolframLang: Find/Replace Script

By Xah Lee. Date: . Last updated: .

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 =
   Module[{content = ReadString[filePath]},
     CopyFile[filePath, StringJoin[filePath, "~", nowDate, "~"],
      OverwriteTarget -> True]];
    WriteString[filePath, StringReplace[content, findReplacePairs]];
    Close[ filePath ]

Scan[ processFile, FileNames[fileNameExtension, inputDir, dirDepth] ]

Print[ "done." ]
  1. Copy and paste into a file and save it as find_replace.wls
  2. Modify the inputDir, and find replace string pairs.
  3. In terminal, run wolframscript -file find_replace.wls

You can also copy and paste it into a Wolfram Notebook .

[see WolframScript Tutorial]


this is with Mathematica version 12.x and 13.2, as of 2023-10-21

Am not sure its a bug, or the script needs to be refined on file encoding and line ending convention. Maybe both.


Find Replace Scripts

WolframLang: Shell Tasks