The sed
command is a powerful tool for finding and replacing text in files on Linux and Unix systems. Here’s how you can use sed
to find and replace text in a file:
- Open a terminal and navigate to the directory containing the file you want to modify.
- Use the following command to find and replace text in a file:
sed 's/<search text>/<replacement text>/g' <file name> > <output file name>
Replace <search text>
with the text you want to find, <replacement text>
with the text you want to replace it with, <file name>
with the name of the file you want to modify, and <output file name>
with the name of the file you want to create as the output. The s/.../.../g
part of the command is called a “substitute command” and it tells sed
to find and replace the specified text. The g
at the end specifies that all occurrences of the text in each line should be replaced (without the g
, only the first occurrence of the text in each line would be replaced).
For example, to find all occurrences of the text “old” and replace them with “new” in the file input.txt
and save the result to a new file output.txt
, you would use the following command:
sed 's/old/new/g' input.txt > output.txt
This command will create a new file with the specified <output file name>
containing the modified text, and the original file will remain unchanged. If you want to modify the original file in place, you can use the following command instead:
sed -i 's/old/new/g' <file name>
Replace <file name>
with the name of the file you want to modify. The -i
option tells sed
to edit the file in place, without creating a backup.