April 23, 2023

Replace all occurences of a word in one or many files from the command line with sed

The following command:

$ sed -i 's/regex/replacement/g' inputfile

replaces all instances of an expression (i.e. regex) by replacement” in a file.

What’s happening in this command?

($ is just here to represent the prompt of the terminal.)

First you tell the shell (terminal) to invoke the utility sed.

Next you invoke the option -i to tell sed to do the replacement in the input file (i.e. not to print the output to the shell).

Next you tell sed that you want to run a replacement of regex’ by replacement’. s, which stands for substitute. /s are just separators. g tells sed to apply the substitution on all occurrences of regex’ throughout the file. If you omit g, sed will only perform the substitution on the first encounter of regex’, leaving following matches unchanged. inputfile is the file where you want to execute the substitution.

What if you want to run the substitution in all Markdown files? Run:

$ sed -i s/regex/replacement/g *.md

What if you want to create a new file with the replacement and keep the input file unedited? Run:

$ sed s/regex/replacement/g inputfile > outputfile

> tells sed to redirect the output of the command to outputfile while inputfile is left unedited.

FYI: > is what is called a redirection, that says from an input file to an output file.

About sed

Sed is a stream editor, that is a utility to perform basic text transformations on an input stream, a file for example. There is a lot more you can do with sed; if you have a repetitive text editing tasks to run, sed might be able to help you. For example, you can delete lines that contains a specific keyword, or add a line to a file (e.g. add an item to a to-do list).

You can run $ man sed or $ info sed to learn more or see some examples.

sed is copyleft-licensed and is currently maintained by Clint Adams1. It was developed from 1973 to 19742.


  1. $ less /usr/share/doc/sed/copyright↩︎

  2. Draft from Michael Hauben and Ronda Hauben netbook titled Netizens: On the History and Impact of Usenet and the Internet.”↩︎


text processing personal computing gnu linux trisquel command-line interface (cli) sed office applications wiki shell literacy

No affiliate links, no analytics, no tracking, no cookies. This work © 2016-2024 by yctct is licensed under CC BY-ND 4.0 .   about me   contact me   all entries & tags   FAQ   GPG public key

GPG fingerprint: 2E0F FB60 7FEF 11D0 FB45 4DDC E979 E52A 7036 7A88