Search code examples
replacefindbatch-processing

Terminal Command for Batch Find and Replace


I have been trying to find how to do a batch find and replace in Terminal on Mac OS X for more than the past hour. I found different versions of code, but am having difficulty making it work. So far, I have found one string of code that works, but it only works for one term/character.

What I want to do is find and replace multiple characters in one text file, all at the same time.

For example:

Find §, replace with ก
Find Ø, replace with ด
Find ≠, replace with ห
Find £, replace with ้

The code that works so far is (but only for one character):

sed -i '' s/Ø/ด/ [textfile.txt]

Could anyone please help me out?


Solution

  • Your pattern of usage is so common that there is a specific utility you can use for it, namely tr

    tr abc ABC < input.txt > output.txt
    

    where you use two strings (here abc and ABC) to instruct tr on the substitutions you want (here, substitute a with A, b with B etc).


    With sed, that's MUCH more general in its usage with respect to tr, to search and replace the first occurrence in every line it is

    sed 's/src1/rep1/' < in > out
    

    to search and replace every occurrence in every line you add a g switch to the s command

    sed 's/src1/rep1/g' < in > out
    

    eventually to do multiple search and replaces you must separate the s commands with a semicolon

    sed 's/src1/rep1/g;s/src2/rep2/;s/src3/rep3/g' < in > out
    

    Note that in the above example I used the g switch (line-wise global substitution) for the 1st and the 3rd find&replace and not for the 2nd one... your usage may be different but I hope that you've spotted the pattern, haven't you?