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 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." ]
  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]

WARNING and bugs

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

xtodo

Find Replace Scripts

WolframLang: Shell Tasks

WolframLang in Depth

Basics

Comment, Print

String

Arithmetic

List

Expression, Atom, Head

Boolean

Conditional

Variable

Loop

Data Structure

Function

Pattern Matching

Advanced

Shell Tasks

Misc