Replacing Text in Files Using `sed` on Linux
If you work with multiple text files on Linux and need to replace specific text within them, the sed
(Stream Editor) tool is a highly useful choice. In this guide, we’ll discuss how to use sed
to efficiently replace text in text files.
What is sed
?
sed
is a command-line tool in Unix/Linux used for editing text in streams of data. It allows you to perform various editing operations such as searching, replacing, deleting, and inserting text.
Example Case: Replacing Text in Text Files
Suppose you have several text files in your directory and want to replace all occurrences of the string abc
with aab
. Here’s how to do it using sed
.
Step 1: Understanding the sed
Command
The basic command used for text replacement with sed
is:
sed 's/pattern/replacement/g'
Here:
s
is the command for substitution.pattern
is the text you want to replace.replacement
is the text that will replace the pattern.g
at the end of the command indicates that the replacement should be applied to all occurrences in the line (global).
Step 2: Using sed
to Replace Text in Files
To replace text in all files with a .txt
extension in your directory, use the following command:
sed -i 's/abc/aab/g' *.txt
Let’s break down this command:
sed
is the command to run the Stream Editor.-i
is an option that tellssed
to perform the replacement directly in the file, without making a copy.'s/abc/aab/g'
is the replacement pattern that searches for the stringabc
and replaces it withaab
.*.txt
specifies that this operation should be applied to all files with a.txt
extension in the current directory.
Practical Example
Suppose you have two text files:
-
file1.txt
containing:abc is a test another abc here
-
file2.txt
containing:abc in this file too
After running the command:
sed -i 's/abc/aab/g' *.txt
Your file contents will be updated to:
-
file1.txt
:aab is a test another aab here
-
file2.txt
:aab in this file too
Tips and Tricks
-
Backup Before Editing: If you want to create a backup of the files before editing, you can use the
-i.bak
option. Example:sed -i.bak 's/abc/aab/g' *.txt
will create a backup file with a.bak
extension before modifying the original files. -
Replacement with Regular Expressions:
sed
also supports regular expressions, allowing for more complex search and replace operations. -
Check Results Before Changing: To preview the replacement results without modifying the files, you can run the command without the
-i
option. Example:sed 's/abc/aab/g' *.txt
.
Conclusion
sed
is a powerful tool for text editing in streams of data. By understanding how to use the replacement command, you can quickly and efficiently edit text across multiple files. Always ensure to check results and create backups if necessary before making permanent changes.