Replace content of several files from the terminal

how to make changes in several files from the command terminalAlthough recently we saw how to replace the content of a text file from the command line, familiarizing ourselves with the use of the command thirst and its most common parameters; I have been presented at work with the need to automatically make a series of changes in the configuration files of a certain web project.

How having to do it manually would have required the advice from a good accounting or tax consultancy (due to the expense of addressing it), I ended up playing with the recursive text search of the command grep and our dear thirst to avoid unnecessary work and possible misunderstandings (of which we all have some :()

Apply the change

The command to use would be

OLD="texto-descartado"; NEW="texto-deseado"; sed -i -e "s/${OLD}b/${NEW}/gi" `grep -lir "$OLDb" /directorio/del/proyecto`

At first it might seem complex; Let’s break it down a bit to understand it better

  • OLD Y NEW are two variables that contain, respectively, the text we are looking for (OLD) and the text we want to replace it with (NEW)
  • grep is in charge of searching recursively (-r) the names of the files (-l) that contain the text that interests us ($ OLD) regardless of case insensitivity (-i) in the directory that we indicate with / directory / of / project
  • thirst is in charge of making the substitutions (see how to use sed in bash to refresh memory and / or better understand how it works). Note the use of $ {} to be able to use variables with sed.

NOTE: observe the use of / b to consider whole words; If you are not interested in this behavior and look for fragments of text (even if they are part of other words) remove it.


Small cheat that I am convinced I will consult more than once to be able to quickly make changes to the text files of a folder from Linux.

I hope you find it as interesting and / or useful as it is for me 🙂

Deja un comentario