Replace text inside files with just one command: perl

On certain occasions we want to replace text within a file, for example, change in Document.txt everything that "my family" says for "us." To achieve this we can use our preferred text editor (Kate, Gedit, SublimeText, etc) but it is always good to know variants, other ways to achieve the same result 🙂

It happens that with regular expressions you can achieve this, the sed command is simply magnificent, it has endless variants and options but ... for those who just want to replace text from the least complex way possible, for them it is that I bring this much simpler variant:

Following the example, we have the file Document.txt located in $ HOME / Document.txt with the following text:

(...) my family it's like all of them, like yours or your neighbor's. In fact my family We try to be responsible people and in the eyes of society, politically and socially correct. However, in my house there is a black sheep, and that is my role LOL !. I have always been the one who is not afraid to say what he thinks (even if it is not apparently correct in the eyes of society), although in reality my family is fed up with the dirt today's society.

With the following command you will change «my family" by " «:

perl -pi -e "s[mi familia][nosotros]g" $HOME/Documento.txt

It's that simple 🙂

So the text would be:

(...) it's like all of them, like yours or your neighbor's. In fact We try to be responsible people and in the eyes of society, politically and socially correct. However, in my house there is a black sheep, and that is my role LOL !. I have always been the one who is not afraid to say what he thinks (even if it is not apparently correct in the eyes of society), although in reality my family is fed up with the dirt today's society.

The syntax is:

perl -pi -e "s[lo-que-quiero-cambiar][lo-nuevo-a-poner]g" archivo-en-el-cual-reemplazar

The command may seem a bit complex, let's break it down a bit and explain it a little more simply 😉

  • perl : What we will use, perl
  • -pi : Pí, how π (the approximate value of 3.14)
  • -e : The E imagine it for «e to execute» (I.e.
  • Then in quotes » we open with a s and we close with a g: "sg" … Imagine the S for Start and the G for Game Over 😀
  • Turn between the sg we must put two sets of brackets: [] y [], being that way: "S [] [] g"
  • Inside the first brackets as I said above, the text that we want to remove and replace with a new one will go, while in the second set of brackets the new text to put will go, following the example: "S [my family] [we] g"

Simple isn't it?

The explanation is actually much more extensive than what is necessary for the command, it is quite simple to understand 🙂

Perl is much, much more than a way to replace text, it's a whole language 😉

If you want to learn more about it, install the package perl-doc and take a look at whooodo what it allows, it's just a different universe.

By the way and to close, assuming you want to find all the .txt files you have in $ HOME / Documents / and in each one replace "my family" with "us", you can join find + perl to achieve this:

find $HOME/Documentos/ -name *.txt -exec perl -p -i -e "s[mi familia][nosotros]g" {} \;

Or using a wildcard:

perl -p -i -e "s[mi familia][nosotros]g" $HOME/Documentos/*.txt

The problem with this second variant is that it will not replace in files that are in subfolders 🙂

Anyway, I hope you found it interesting. For me it has been really useful, I can already replace text directly from the terminal ... great! 😀


The content of the article adheres to our principles of editorial ethics. To report an error click here!.

21 comments, leave yours

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.   boom said

    Well, I think many of us here know the sed command, which serves the same purpose, it does it much better and is easier to use ...

    1.    KZKG ^ Gaara said

      Thanks for your comment,
      Just two details, why do you say that sed makes it better? Is it really easier to use with so many 'weird' characters?

  2.   Federico A. Valdés Toujague said

    Greetings to all!!!. I have used the command thirst, and the method described here with perl is simpler. Thanks KZKG ^ Gaara !!!.

    1.    KZKG ^ Gaara said

      Thanks for the comment 🙂
      Well, at least to me this seems simpler than regular expressions ... that with so many 'weird' characters, something really complex to understand and learn can be done to the non-savvy.

      1.    Giskard said

        There is an «old» adage out there: «I had a problem, I decided to use Regular Expressions ... now I have TWO problems» 😉

        1.    KZKG ^ Gaara said

          HAHAHAHAHAHAHA !!!
          Regular expressions can save our lives at a certain point ... yes, it takes a long time to learn how to use them and not die trying.

          If I had known this command years ago, GOD !! how simple my life would have been 😀

          1.    Giskard said

            Clear! Well handled they are very powerful 🙂 Nothing better to manipulate text. But sometimes, as you say in this case with Perl, you don't have to go that far if a replace is enough.
            I would have used Python anyway :)

    2.    dhunter said

      But in thirst I see it even simpler ... am I doing something wrong?

      sed -i "yes / what-I-want-to-change / new-to-put /" file-in-which-to-replace

      1.    KZKG ^ Gaara said

        heh heh ... and if I want to replace "http://my.blog.com/content/" with "http://my.blog.com/uploads/files/" 😀 ... already there you have to put \ with spaces and others , and it becomes complex or not?

        1.    dhunter said

          It is not mandatory to use / as a separator. Look with +

          sed -i «s + http: //my.blog.com/content/+http: //my.blog.com/uploads/files/+» file

          1.    KZKG ^ Gaara said

            O_O… WTF!
            You have opened a whole universe of options for me now .. O_O

          2.    Giskard said

            I love these posts where we all learn something 🙂
            I didn't know that either.

  3.   RAW-Basic said

    I prefer to use directly vi ..

    As simple as:
    :% s / us / my family / g

    % -> whole document
    s -> search
    g -> all occurrences

    Greetings ..

    1.    KZKG ^ Gaara said

      Thank you!
      I didn't know how to do it with vi

  4.   st0rmt4il said

    Added to favorites!

    Thank you!

  5.   DuranG said

    Great entry! In case anyone is interested, the same with the Linux sed command: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html

    1.    Doubting said

      And what happens if within the file what I want to replace has quotes?
      Example replace what says text: »1 ″ by text:» 2 ″
      how would the command be?

  6.   Percy salgado said

    Hello

    I wanted to replace a string that had an @ in the middle and only changed the text to the before the at.

    text to change: Viva el Perú
    new text: Viva mi patria @percysalgado
    Shown: Long live my homeland

    Thanks for your help

  7.   Anonymous said

    "\" You must use the slash before the characters with double use @, #, so that they are interpreted as text.

  8.   Gaba said

    And how do I do it in windows ????