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
inputfile is left unedited.
> is what is called a redirection, that says from an input file to an output file.
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.
I do self-funded research and I'm writing a book.
> What's the book about?
About technologies and epistemology.
Meaning, technologies can foster agency. No doubt. But I am also asking:
Can technologies make us blind?
I posted a summary of the prologue on the homepage: https://yctct.com/