The Wayback Machine - https://web.archive.org/web/20240919052415/https://www.geeksforgeeks.org/sed-command-linux-set-2/
Open In App

SED command in Linux | Set 2

Last Updated : 23 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We have discussed some of the SED command options in Sed Command in Linux/Unix with examples 

SED is used for finding, filtering, text substitution, replacement and text manipulations like insertion, deletion search, etc. It’s a one of the powerful utilities offered by Linux/Unix systems. We can use sed with regular expressions. I hope atleast you have the basic knowledge about Linux regular expressions. 

It provides Non-interactive editing of text files that’s why it’s used to automate editing and has two buffers – pattern buffer and hold buffer. Sed use Pattern buffer when it read files, line by line and that currently read line is inserted into pattern buffer whereas hold buffer is a long-term storage, it catch the information, store it and reuse it when it is needed. Initially, both are empty. SED command is used for performing different operations without even opening the file. 

sed general syntax – 
sed OPTIONS… [SCRIPT] [INPUTFILE…] 

First create a.txt file on which I am going to perform operations for SED commands. In this blog, I used “a.txt” file to explain all the examples. Blog will become too long if i write the output of each sed command. So, you may refer the same file to practice all the commands initially.  

[root@rhel7 ~]# cat a.txt
life isn't meant to be easy, life is meant to be lived.
Try to learn & understand something new everyday in life.
Respect everyone & most important love everyone.
Don’t hesitate to ask for love & don’t hesitate to show love too.
Life is too short to be shy.
In life, experience will help you differentiating right from wrong.

# Let’s start with File Spacing 
1 – Insert one blank line after each line –  

[root@rhel7 ~]# sed G a.txt 

sed-output

2 – To insert two blank lines –  

[root@rhel7 ~]# sed 'G;G' a.txt

3 – Delete blank lines and insert one blank line after each line –  

[root@rhel7 ~]# sed '/^$/d;G' a.txt

4 – Insert a black line above every line which matches “love” –  

[root@rhel7 ~]# sed '/love/{x;p;x;}' a.txt

5 – Insert a blank line below every line which matches “love” –  

[root@rhel7 ~]# sed '/love/G' a.txt

6 – Insert 5 spaces to the left of every lines –  

[root@rhel7 ~]# sed 's/^/     /' a.txt

# Numbering lines 
1 – Number each line of a file (left alignment). **=** is used to number the line. \t is used for tab between number and sentence – 

[root@rhel7 ~]# sed =  a.txt | sed 'N;s/\n/\t/'

2 – Number each line of a file (number on left, right-aligned). This command is similar to `cat -n filename`. 

[root@rhel7 ~]# sed = a.txt | sed 'N; s/^/     /; s/ *\(.\{4,\}\)\n/\1  /'

3 – Number each line of file, only if line is not blank –  

[root@rhel7 ~]#  sed '/./=' a.txt | sed '/./N; s/\n/ /'

# Deleting lines 
1 – Delete a particular line – 
Syntax: sed ‘nd’ filename 
Example :  

[root@rhel7 ~]# sed '5d' a.txt

2 – Delete the last line 
Syntax: sed ‘$d’ filename 

3 – Delete line from range x to y 
Syntax: sed ‘x,yd’ filename 
Example :  

[root@rhel7 ~]# sed '3,5d' a.txt

4 – Delete from nth to last line 
Syntax: sed ‘nth,$d’ filename 
Example : 

[root@rhel7 ~]# sed '2,$d' a.txt

5 – Delete the pattern matching line – 
Syntax: sed ‘/pattern/d’ filename 
Example :  

[root@rhel7 ~]# sed '/life/d' a.txt

6 – Delete lines starting from nth line and every 2nd line from there – 
Syntax: sed ‘n~2d’ filename 
Example :  

[root@rhel7 ~]# sed '3~2d' a.txt

7 – Delete the lines which matches the pattern and 2 lines after to that – 
Syntax: sed ‘/pattern/,+2d’ filename 
Example :  

[root@rhel7 ~]# sed '/easy/,+2d' a.txt

8 – Delete blank Lines  

[root@rhel7 ~]# sed '/^$/d' a.txt

9 – Delete empty lines or those begins with “#” –  

[root@rhel7 ~]# sed -i '/^#/d;/^$/d' a.txt

# View/Print the files 
If we want to view content of file, then we use cat command and if we want to view the bottom and the top content of any file, we use tools such as head and tail. But what if we need to view a particular section in the middle of any file? Here we’ll discuss, how to use SED command to view a section of any file. 

1 – Viewing a file from x to y range – 
Syntax: sed -n ‘x,yp’ filename 
Example : 

[root@rhel7 ~]# sed -n '2,5p' a.txt

2 – View the entire file except the given range – 
Syntax: sed ‘x,yd’ filename 
Example :  

[root@rhel7 ~]# sed '2,4d' a.txt

3 – Print nth line of the file – 
Syntax: sed -n ‘address’p filename 
Example :  

[root@rhel7 ~]# sed -n '4'p a.txt

4 – Print lines from xth line to yth line. 
Syntax: sed -n ‘x,y’p filename 
Example :  

[root@rhel7 ~]# sed -n '4,6'p a.txt

5 – Print only the last line – 
Syntax: sed -n ‘$’p filename 

6 – Print from nth line to end of file – 
Syntax: sed -n ‘n,$p’ filename 
Example : 

[root@rhel7 ~]# sed -n '3,$'p a.txt

Pattern Printing 
7 – Print the line only which matches the pattern – 
Syntax: sed -n /pattern/p filename 
Example : 

[root@rhel7 ~]# sed -n /every/p a.txt

8 – Print lines which matches the pattern i.e from input to xth line. 
Syntax: sed -n ‘/pattern/,xp’ filename 
Example :  

[root@rhel7 ~]# sed -n '/everyone/,5p' a.txt

Following prints lines which matches the pattern, 3rd line matches the pattern “everyone”, so it prints from 3rd line to 5th line. Use $ in place of 5, if want to print the file till end. 

9 – Prints lines from the xth line of the input, up-to the line which matches the pattern. If the pattern doesn’t found then it prints up-to end of the file. 
Syntax: sed -n ‘x,/pattern/p’ filename 
Example : 

sed -n '1,/everyone/p' a.txt

10 – Print the lines which matches the pattern up-to the next xth lines – 
Syntax: sed -n ‘/pattern/,+xp’ filename 
Example :  

sed -n '/learn/,+2p' a.txt

# Replacement with the sed command 
1 – Change the first occurrence of the pattern – 

[root@rhel7 ~]# sed 's/life/leaves/' a.txt

2 – Replacing the nth occurrence of a pattern in a line – 
Syntax: sed ‘s/old_pattern/new_pattern/n’ filename 
Example :  

[root@rhel7 ~]# sed 's/to/two/2' a.txt

We wrote “2” because we replaces the second occurrence. Likewise you can use 3, 4 etc according to need. 

3 – Replacing all the occurrence of the pattern in a line.  

[root@rhel7 ~]# sed 's/life/learn/g' a.txt

4 – Replace pattern from nth occurrence to all occurrences in a line. 
Syntax: sed ‘s/old_pattern/new_pattern/ng’ filename 
Example :  

[root@rhel7 ~]# sed 's/to/TWO/2g' a.txt

Note – This sed command replaces the second, third, etc occurrences of pattern “to” with “TWO” in a line. 

If you wish to print only the replaced lines, then use “-n” option along with “/p” print flag to display only the replaced lines – 

[root@rhel7 ~]# sed -n 's/to/TWO/p' a.txt

And if you wish to print the replaced lines twice, then only use “/p” print flag without “-n” option-  

[root@rhel7 ~]# sed 's/to/TWO/p' a.txt

5 – Replacing pattern on a specific line number. Here, “m” is the line number. 
Syntax: sed ‘m s/old_pattern/new_pattern/’ filename 
Example :  

[root@rhel7 ~]# sed '3 s/every/each/' a.txt

If you wish to print only the replaced lines –  

[root@rhel7 ~]# sed -n '3 s/every/each/p' a.txt

6 – Replace string on a defined range of lines – 
Syntax: sed ‘x,y s/old_pattern/new_pattern/’ filename 
where, 
x = starting line number 
and y = ending line number 

Example : 

[root@rhel7 ~]# sed '2,5 s/to/TWO/' a.txt

Note – $ can be used in place of “y” if we wish to change the pattern up-to last line in the file. 
Example :  

[root@rhel7 ~]# sed '2,$ s/to/TWO/' a.txt

7 – If you wish to replace pattern in order to ignore character case (beginning with uppercase or lowercase), then there are two ways to replace such patterns – 
First, By using “/i” print flag – 
Syntax: sed ‘s/old_pattern/new_pattern/i’ filename 
Example :  

[root@rhel7 ~]# sed 's/life/Love/i' a.txt

Second, By using regular expressions –  

[root@rhel7 ~]# sed 's/[Ll]ife/Love/g' a.txt

8 – To replace multiple spaces with a single space –  

[root@rhel7 clang]# sed 's/  */ /g' filename

9 – Replace one pattern followed by the another pattern – 
Syntax: sed ‘/followed_pattern/ s/old_pattern/new_pattern/’ filename 
Example :  

[root@rhel7 ~]# sed '/is/ s/live/love/' a.txt

10 – Replace a pattern with other except in the nth line. 
Syntax: sed ‘n!s/old_pattern/new_pattern/’ filename 
Example :  

[root@rhel7 ~]# sed -i '5!s/life/love/' a.txt

 



Similar Reads

Sed Command in Linux/Unix with examples
SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is much quicker way to find and replace somethi
7 min read
Find and Replace with sed in Directory and Sub Directories in Linux
sed stands for stream editor. It is a basic utility command in Linux that has basic functionality like inserting, deleting, finding, replacing, and searching text strings in a file. But sed is most commonly used for its substitution function i.e find and replace. Syntaxsed OPTIONS... [script] [input_file] e.g. sed "s/abc/ABC/g" abc.txt Consider the
4 min read
Ccat – Colorize Cat Command Output command in Linux with Examples
ccat is a command-line tool for Linux and OSX, which is similar to the cat command in Linux. But the difference between cat and ccat is that the ccat shows the content of the file with the syntax highlighted. Currently, ccat supports the following programming languages. JavaScriptJavaRubyPythonGoCJSONInstallation of Ccat First, we are going to see
2 min read
How to Display Command History in Linux | history Command
The command-line interface in Linux provides powerful tools for users, and mastering command history is essential for efficient navigation and retrieval of previously executed commands. The history command is a valuable utility that allows users to view and search through their command history. In this comprehensive guide, we will explore the vario
4 min read
How to Display and Set Date and Time in Linux | date Command
date command is used to display the system date and time. date command is also used to set date and time of the system. By default the date command displays the date in the time zone on which unix/linux operating system is configured.You must be the super-user (root) to change the date and time.  Syntax of Date Command in Linux date [OPTION]... [+F
6 min read
select command in Linux with examples
select command in Linux is used to create a numbered menu from which a user can select an option. If the user enters a valid option then it executes the set of command written in select block and then ask again to enter a number, if a wrong option is entered it does nothing. If user enters nothing and simply press 'enter' the option menu gets print
1 min read
atrm command in Linux with examples
atrm command is used to remove the specified jobs. To remove a job, its job number is passed in the command. A user can only delete jobs that belong to him. Only superuser can delete any job even if that belongs to another user. Syntax: atrm [-V] job [job...] Options: -V : Used to print the version number atrm -V job : Job number of the job which i
1 min read
expand Command in LINUX with examples
Whenever you work with files in LINUX there can be a situation when you are stuck with a file containing many tabs and whatever you need to do with a file requires that file with no tabs but with spaces. In this situation, the task looks quite simple if you are dealing with a small file but what if the file you are dealing with is very big or you n
3 min read
rcp Command in Linux with examples
There comes a time while using LINUX when there is a need to copy some information stored in a file to another computer. This can be done simply using rcp command line utility . Obviously there exists some other methods to complete the above mentioned task which are more secure (like scp or rsync) but this command lets you do this in the simple way
4 min read
du Command in LINUX
While working on LINUX, there might come a situation when you want to transfer a set of files or the entire directory. In such a case, you might wanna know the disk space consumed by that particular directory or set of files. As you are dealing with LINUX, there exists a command line utility for this also which is du command that estimates and disp
9 min read
dmesg command in Linux for driver messages
dmesg command also called as "driver message" or "display message" is used to examine the kernel ring buffer and print the message buffer of kernel. The output of this command contains the messages produced by the device drivers. Usage of dmesg : When the computer boots up, there are lot of messages(log) generated during the system start-up. So you
5 min read
fmt command in Linux with examples
fmt command in LINUX actually works as a formatter for simplifying and optimizing text files. Formatting of text files can also be done manually, but it can be really time-consuming when it comes to large text files, this is where fmt comes to rescue. fmt re-formats each paragraph in the file specified, writing to standard output. Here's the syntax
4 min read
unexpand command in Linux with Examples
To convert the leading spaces and tabs into tabs, there exists a command line utility called unexpand command. The unexpand command by default convert each spaces into tabs writing the produced output to the standard output. Here's the syntax of unexpand command : Syntax : $unexpand [OPTION]... [FILE]... where, OPTION refers to the options compatib
2 min read
uniq command in Linux with examples
The linux uniq command is basically used to remove all repeated lines in a file. This command is used when a line is repeated multiple times and replace these multiple lines with one line. This command is designed to work on sorted files. Purpose : Remove repetitious lines from the sorted 'input-file' and send unique lines to the 'output-file'. If
2 min read
anacron command in linux with examples
anacron command is used to execute commands periodically with a frequency specified in days. Its main advantage over cron is that it can be used on a machine which is not running continuously. In cron if a machine is not running on time of a scheduled job then it will skip it, but anacron is a bit different as it first checks for timestamp of the j
3 min read
enable and disable command in Linux
Enables and disables are the built-in shell commands. enable command is used to start the printers or classes whereas the disable command is used to stop the printers or classes. Syntax For enable Command: enable [-a] [-dnps] [-f filename][name ...] Syntax For disable Command: disable [-c] [-W] [ -r [ reason ] ] printer Options: -a : List all built
1 min read
for command in Linux with Examples
for command in Linux is used to repeatedly execute a set of command for every element present in the list. Syntax: for NAME [in WORDS ... ] ; do COMMANDS; done Example: Options: help for : It displays help information.
1 min read
autoheader command in Linux with Examples
autoheader command in Linux is used to create a template file of C "#define" or any other template header for configure to use. If the user will give autoheader an argument, it reads the standard input instead of reading configure.ac and also writes the header file to the standard output. This command scans the configure.ac file and figures out whi
1 min read
expect command in Linux with Examples
expect command or scripting language works with scripts that expect user inputs. It automates the task by providing inputs. // We can install expect command using following if not installed // On Ubuntu $sudo apt install expect // On Redhat based systems $ yum install expect First we write a script that will be needing inputs from users and then we
2 min read
function command in Linux with examples
The function is a command in Linux that is used to create functions or methods. It is used to perform a specific task or a set of instructions. It allows users to create shortcuts for lengthy tasks making the command-line experience more efficient and convenient. The function can be created in the user's current shell session or saved in the shell
2 min read
fg command in Linux with examples
fg command in linux used to put a background job in foreground. Syntax: fg [job_spec] job_spec may be: %n : Refer to job number n. %str : Refer to a job which was started by a command beginning with str. %?str : Refer to a job which was started by a command containing str. %% or %+ : Refer to the current job. fg and bg will operate on this job if n
1 min read
bg command in Linux with Examples
bg command in linux is used to place foreground jobs in background. Syntax: bg [job_spec ...] job_spec may be: %n : Refer to job number n. %str : Refer to a job which was started by a command beginning with str. %?str : Refer to a job which was started by a command containing str. %% or %+ : Refer to the current job. fg and bg will operate on this
1 min read
Clear Command in Linux with Examples
clear is a standard Unix computer operating system command that is used to clear the terminal screen. This command first looks for a terminal type in the environment and after that, it figures out the terminfo database for how to clear the screen. And this command will ignore any command-line parameters that may be present. Also, the clear command
2 min read
Continue Command in Linux with examples
continue is a command which is used to skip the current iteration in for, while, and until loop. It is used in scripting languages and shell scripts to control the flow of executions. It takes one more parameter [N], if N is mentioned then it continues from the nth enclosing loop. The syntax for the `continue` command in Linuxcontinue or continue [
2 min read
hostid command in Linux with examples
hostid is a command in Linux that is used to display the Host's ID in hexadecimal format. It provides a quick and straightforward way to retrieve the host ID, allowing administrators to associate it with software licenses or perform system-specific operations. Syntax of `hostid` command in Linuxhostid [OPTION] Options provided by hostedhostid --hel
1 min read
Dirname Command in Linux with Examples
dirname is a command in Linux that is used to remove the trailing forward slashes "/" from the NAME and prints the remaining portion. If the argument NAME does not contain the forward slash "/" then it simply prints dot ".". In other words, we can say that the `dirname` command is a useful tool for extracting the directory portion from a given path
2 min read
sdiff command in Linux with Examples
sdiff command in linux is used to compare two files and then writes the results to standard output in a side-by-side format. It displays each line of the two files with a series of spaces between them if the lines are identical. It displays greater than sign if the line only exists in the file specified by the File2 parameter, and a | (vertical bar
2 min read
factor command in Linux with examples
The factor command in Linux is used to print the prime factors of the given numbers, either given from command line or read from standard input. The numbers given through standard input may be delimited by tabs, spaces or newlines. Syntax: factor [NUMBER] Factor 100 (non-prime number): We get the prime factors 2 and 5 that make up 100. Factor 13 (p
1 min read
chpasswd command in Linux with examples
chpasswd command is used to change password although passwd command can also do same. But it changes the password of one user at a time so for multiple users chpasswd is used. Below figure shows the use of passwd command. Using passwd we are changing the password of the guest user. Here first you have to enter the password of the currently signed u
2 min read
biff command in Linux
biff is a mail notification system for unix that notifies the user at the command line when new mail arrives and tells from whom it is. Syntax: biff [ y | n ] Options: Y : This option is to enable the mail notification. N : This option is to disable the mail notification. Note: When mail notification is enabled, the header and first few lines of th
1 min read
Article Tags :