Sed

Learn how to find and replace regexes like a pro.

At the end of this article you will find a copy of the first sentence of Sherlock Holmes, The Hound of the Baskervilles taken from WikiSource. This will be used to demonstrate the power of sed. Copy this sentence into a text file called "hound.txt".

  • Substitution with sed 's/textToReplace/textToInsert/' fileName.txt. This command will replace the given text pattern with the replacement pattern in the text file. By default this substitution will only take place on the first match of each line.

                                $ sed 's/was/WAS/' hound.txt
                                MR. SHERLOCK HOLMES, who WAS usually very late in the mornings, save upon those not infrequent occasions when he stayed up all night, was seated at the breakfast table.
                                $
                                
  • If you want to replace all occurrences of a regex then you can use the "global" g flag. sed 's/textToReplace/textToInsert/g' fileName.txt.

                                $ sed 's/was/WAS/' hound.txt
                                MR. SHERLOCK HOLMES, who WAS usually very late in the mornings, save upon those not infrequent occasions when he stayed up all night, WAS seated at the breakfast table.
                                $
                                
  • The "write" w flag allows us to output our new text to a file. sed 's/textToReplace/textToInsert/w fileNameOut.txt' fileName.txt.

                                $ sed 's/SHERLOCK/JEFF/w hound2.txt' hound.txt
                                MR. SHERLOCK HOLMES, who WAS usually very late in the mornings, save upon those not infrequent occasions when he stayed up all night, WAS seated at the breakfast table.
                                $ cat hound2.txt
                                MR. JEFF HOLMES, who was usually very late in the mornings, save upon those not infrequent occasions when he stayed up all night, was seated at the breakfast table.
                                $
                                

Another useful sed function is the -n flag: -n suppresses sed's standard output. Use like this:

                    $ sed -n 's/textToReplace/textToInsert/' fileName.txt
                    $
                    

This is the first sentence of Authur Conan Doyle's Sherlock Holmes book, The Hound of the Baskervilles.


MR. SHERLOCK HOLMES, who was usually very late in the mornings, save upon those not infrequent occasions when he stayed up all night, was seated at the breakfast table.