sed Command in Linux for Editing Files
The sed Command in Linux is a powerful stream editor for searching, replacing, inserting, and deleting text directly in files without opening them. It supports regular expressions for advanced pattern matching, enabling efficient text manipulation.
🤖AI Overview:
The sed Command in Linux functions as a versatile stream editor that allows users to perform quick and automated text transformations on files or input streams through the command line. It supports both basic and extended regular expressions, making it a valuable tool for Linux system administrators and developers to manipulate and process text efficiently within scripts or batch jobs.
What is Linux sed Command and How to Use it
For editing text in files and streams, the Linux sed tool provides an effective text editor without a GUI. The sed command in Linux can choose, change, add, remove, and edit text in files and streams while giving it guidelines to follow. Regular expressions are frequently utilized by sed for pattern matching and text selection, therefore familiarity with regexes is crucial for efficient use of sed.
Before going through this guide and learning all you need to know about sed Command in Linux, take a look at the main syntax of the Linux sed command:
sed OPTIONS... [SCRIPT] [INPUTFILE...]
The sed Command Options in Linux
To use sed command in ubuntu linux, you can run the command-line options shown below:
sed Command
| Usage |
-b, --binary | Open input files in binary mode to consider lines to end at a line feed. |
-debug | Switch to debug mode to print input in canonical form and annotate program execution. |
--follow-symlinks | Edit the ultimate destination if the specified file is a symbolic link. It only works when combined with the -i option. |
--help | Display the usage information. |
--i, --in-place [=SUFFIX] | Perform edits in-place by overwriting the original file. |
--posix | Disable all extensions to POSIX sed to simplify writing portable scripts. |
--version | Display the version of sed running on the system. |
-E, -r, --regexp-extended | Use extended regular expressions. |
-e script, --expression=script | Add a specified script to run with the commands. |
-f script-file | Add the contents of a specified script-file to run with the commands. |
-l N, --line-length=N | Define the desired line-wrap length for the l command (default value is 70). |
-n, --quiet, --silent | Disable output printing. |
-s, --separate | View specified files as separate, not as a single continuous long stream. |
--sandbox | Disable running external programs and operate only on input files on the command line. |
-u, --unbuffered | Minimalize input and output buffer. |
-z, --null-data, --zero-terminated | View input as a set of lines where each ends with a zero byte. |
You just need to take 15 minutes to read this guide and start using the power of sed command.
Most Used sed Command in Linux to Edit Files
This tutorial covers 15 examples of sed command in Linux to let you prepare using this helpful command when you need to do your administrative tasks such as editing files. Before using the below commands on your crucial files, make sure to test them thoroughly.
1. Using sed Command to Replace String
The Linux sed command is most frequently used for replacing text. It looks through a file for the given pattern and replaces it with the desired string. Using sed command, you can replace a string in a file. The syntax is:
sed 's/old_string/new_string/g' file_name
To replace string, you just need to replace old_string
with the considered text to be substituted and replace new_string
with the text you want to change it to. For example, to replace ”morning” with ”evening”, run the following command:
sed 's/morning/evening/g' nightshift.txt
The “nightshift.txt” file’s contents are read by this command, which then changes every instance of the word “morning” to the word “evening” and publishes the modified text to the terminal. The g
flag instructs the command to replace any instances of the match throughout the whole file.
Also, the -i
argument can be used to make changes in place and the substitution command ‘s‘, the original string, and the replacement string must all be included in the command string.
To make the changes in the above file with the sed -i option, you can run the command as below:
sed -i 's/morning/evening/g' nightshift.txt
You’ll see that the original file has been altered. Before making modifications to the original file, you can also create a backup of the file.
sed -i.bak 's/morning/evening/g' nightshift.txt
In this way, a backup file of the original will be created in the current directory with the name nightshift.txt.bak
.
2. Using sed Command to Replace Each Line’s First Occurrence
The sed command in Linux only replaces the first instance of the given string in each line by default. In each line, it looks for the first occurrence of the specified term, replaces it, and then moves on to the next line. You can use the s/pattern/replacement/ command to replace only the first instance of a pattern on each line. For instance, you may use the command below to only change the first instance of the word “morning” in the file nightshift.txt with the word “evening”:
sed 's/morning/evening/' nightshift.txt
3. Replace Each Line’s Last Occurrence Using sed Command in Linux
With the ‘s/pattern/replacement/g’ command, you can replace only the final instance of a pattern on each line. For instance, you may use the command below to only change the word “morning” where it appears in the file nightshift.txt’s last instance with the word “evening”:
sed 's/\(.*\)morning/\1evening/g' nightshift.txt
4. Using sed Command to Replace Particular Occurrence in a Line
The lineNumbers/pattern/replacement/ command can be used to replace a string on a certain line. For instance, you may use the below sed command in Linux to change the word “morning” to the word “evening” on line 3 of the file nightshift.txt:
sed '3s/morning/evening/' nightshift.txt
5. Replace String from Range of Line Numbers with Linux sed Command
You can use the startLineNumber,endLineNumber/pattern/replacement/ command to replace a string across a number of lines. For instance, you may use the command below to change the term “morning” to the word “evening” on lines 3 through 5 of the file nightshift.txt:
sed '3,5s/morning/evening/' nightshift.txt
6. Only Print Line Numbers
The sed command use in Linux is also for printing lines from a file. ‘/pattern/=’ can be used to output only the line numbers of lines that match. For instance, the following sed command in Linux can be used to output the line numbers of all lines in the file nightshift.txt that have the word “morning” in them:
sed '/morning/=' nightshift.txt
7. Print the file range with sed Command
The ‘start,endp’ commands can be used to print a range of lines. For instance, you can use sed -n option in Linux to print the first 10 lines of the file nightshift.txt:
sed -n '1,10p' nightshift.txt
8. Add a New Line after Matching Pattern
You can use the command /pattern/anewline to add a line after a certain pattern. For instance, you may use the command below to add the word “midnight” after the line that includes the word “morning” in the file nightshift.txt.
sed '/morning/a\midnight' nightshift.txt
9. Add a New Line before Matching Pattern
Using the command /pattern/inewline, you can add a line before a specific pattern. For instance, you may use the command below to place the word “midnight” before the word “morning” in the file nightshift.txt.
sed '/morning/i\midnight' nightshift.txt
10. Change the Case of Characters in Linux Using sed Command
You can use the ‘y/old/new/’ command to change a string’s case. For instance, you may use the command below to convert all lowercase letters in the nightshift.txt file to uppercase:
sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' nightshift.txt
11. Delete the First Line From File
So far, you reviewed 10 sed command examples in Linux. For the 11th example till the end, we will explain how to delete lines in a file using sed command in Linux. Use the /pattern/d command to remove a line that includes a specific string. For instance, you can use the following command to remove any lines from the file nightshift.txt that contain the word “morning”:
sed '1d' nightshift.txt
12. Delete Line Contains Specified String
The ‘/pattern/d’ command can be used to delete a line that includes a specific string. To erase all lines containing the word “morning” in the file nightshift.txt, for example, execute the following command:
sed '/morning/d' nightshift.txt
13. Delete All Lines Except the Matching String
You can combine other commands with the ‘!‘ operator to reverse the matched lines. For instance, you can use the following command to remove any lines from the file nightshift.txt that contain the word “morning”:
sed '/morning/!d' nightshift.txt
14. Delete the Lines that are Mentioned
To delete a specific amount of lines, use the startLineNumber
, endLineNumber <strong>d</strong>
command. To remove lines 3 through 5 from the text file nightshift.txt, for instance, run the command shown below:
sed '3,5d' nightshift.txt
15. Delete Empty Lines From File with sed Command
The sed Command in Linux can also be used to delete the empty lines from the file. Run the following command to remove the empty lines from a file:
sed '/^$/d' nightshift.txt
This command treats any line devoid of any characters—not even a single space—as empty.
Conclusion
The sed Command in Linux is an essential tool for developers managing text files and streams efficiently. Its ability to search, replace, insert, delete, and print text without manual editing accelerates workflow and eases handling complex patterns through regex.
Understanding its syntax, options, and best practices ensures safe, effective text edits across various Linux distributions such as Ubuntu, Debian, and CentOS.
With practice, mastery of the sed Command in Linux enables developers to automate configuration management, perform codebase modifications, and process logs proficiently.
It is highly recommended to combine sed commands with backups and testing to minimize risk when modifying critical data.
FAQ
2. How does the sed Command differ from traditional text editors?
Sed operates non-interactively by processing input line by line using scripted commands, unlike traditional editors that require manual editing after opening the entire file.
3. What common use cases exist for sed in Linux development?
Sed is commonly used for batch editing configuration files, automating text replacements in scripts, manipulating log files, and performing complex text processing tasks using regular expressions.
4. How can I replace a string in a file using sed?
Use the syntax "sed s/old_string/new_string/g filename" to replace all occurrences, and add "-i" to edit the file in place, for example:
sed -i s/old/new/g filename
5. Can sed replace text only on specific lines or ranges?
Yes. You can specify line numbers or ranges with syntax such as "sed 3s/old/new/" for line 3 or "sed 3,5s/old/new/" for lines 3 through 5.
6. Does sed support backups when editing files in place?
Yes. When using the "-i" option, you can create backups by providing a suffix, e.g., "sed -i.bak s/old/new/g filename" creates a backup file named "filename.bak".
7. How does sed handle pattern matching?
Sed uses regular expressions for powerful pattern matching, allowing complex searches and replacements.
8. Can sed add or delete lines based on patterns?
Yes. It can append or insert lines before or after matching patterns and delete lines matching a pattern or specific line numbers.
9. Is it possible to change character case with sed?
Yes. The "y" command within sed can translate characters from lowercase to uppercase or vice versa.
10. How do I print specific lines with sed?
Use "sed -n start,endp" to print specific lines or "sed /pattern/=" to print line numbers of matching lines.