linux – Find and Replace Multiple Words Within a File

Question:

I want to develop a script that will replace any words in the .

I know I can do it with the command(s) below:

$ tr 'ABC' '123' < arquivo.txt > novo-arquivo.txt

or

$ sed "s/ABC/123/g" arquivo.txt > novo-arquivo.txt

However, I don't just want to change one "word" for "another", but rather, make several changes of several " words " inside the file(document)

For example:

I would like the script to perform mass replacement .. group/set words that will be defined by the user himself.

Suppose the file(document) contains the following words:

  • man
  • Sun
  • day

So the script should ask the question about the proper exchange, something like this:

1) – Type here all the words you want to replace them with: man, sun, day

2) – Now, type in the same order as before, the new ones to be inserted: woman, moon, night

That is, to automate change in general, instead of replacing just a single word, it can be more than one in different occurrences.

Conclusion

So it would be enough to be defined by the user, to make the change in the file itself simultaneously (at once). Change a set of words for others that the user will be able to define.

Answer:

To get the words to be replaced from the user input and put them in an array , do like this:

palavras=()
while IFS= read -r -p "Digite a palavra ([ENTER] para terminar): " linha; do
    [[ $linha ]] || break
    palavras+=("$linha")
done

Assuming you have the arrays of words to replace and substitutes:

substituir=( "homem" "sol" "dia" )
substituto=( "mulher" "lua" "noite" )

Use a for loop to iterate over one of the arrays , and with sed you do the substitution:

for ((i=0; i<${#substituir[@]}; ++i)); do
    printf "Substituindo ${substituir[i]} por ${substituto[i]}...\n"

    sed -i "s/${substituir[i]}/${substituto[i]}/" foo.txt
done

View DEMO

Note : If you need the substitution done globally, add the g modifier after the second delimiter.

You can also use Perl, in one line:

perl -i -pe 's/homem/mulher/g; s/sol/lua/g; s/dia/noite/g' foo.txt 

The i option basically indicates that changes will be made to the file. p is used to iterate over the file, e indicates the code to be executed, in this case s/.../... . More information .

Scroll to Top