How to find and replace text in multiple files from the terminal

Search and Replace text can be a simple task using the text editors more basic. But what happens when you need to do that same task in multiple files at the same time?

Well, things get complicated there ... or not so much.


In the following example, we will use sed to replace all occurrences of the word "mongo" with the word "aurelio" in all files that have the extension .txt and that are in the / home / user / myfolder / folder.

find / home / user / myfolder / -name * .txt -exec sed -i "s / mongo / aurelio / g" {} \;

That easy…

Before finishing, it is worth mentioning that some text editors allow this operation to be carried out using a graphical interface. Among others, it is worth highlighting Jedit, Geany, Regexxer, etc.


Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   TSH said

    Great

  2.   Skeptical said

    I use the Gedit

    1.    mrlon said

      gedit for multiple files ??? as???

  3.   ron said

    How could I put a grep in between ai?

    What I need is to do the following, search inside home for all the files that are called index.html and that contain the word "XXXXXXX", and replace it with "YYYYYYYYYY", as it could be done so that it only searches in the files that actually have the string?

    Thank you so much !

  4.   MelhorHospedagem said

    I use the Gedit too, but thank you very much

  5.   Angel Garcia said

    You are missing the argument for exec. The correct code would be:
    find / home / username / myfolder / -name * .txt -exec sed -i "s / mongo / aurelio / g" {} \;

    Greetings 😀

    1.    let's use linux said

      You are right! Thank you!
      I already corrected it. : =)

  6.   gardo said

    I just tried this (as ROOT):

    find / usr / share / icons / ACYL-Allgray / -name * .svg -exec sed -i "s / 666666/000000 / g" {} \;

    to change the color of an entire set of icons. The truth is that it is a very powerful command, normally this task would have taken me hours editing file by file.

  7.   Edmundo said

    Insert text in several files, according to the line number, in my case line 2 (2i), in centos linux

    find / home // public_html / res / -name -exec sed -i "2i \;" {} \;

    1.    Edmundo said

      not all the code came out so I resubmitted:

      find / home / user / public_html / res / -name filename.ext -exec sed -i "2i \ text to insert" {} \;