The Wayback Machine - https://web.archive.org/web/20241126212318/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
The SED (Stream Editor) command in Unix/Linux is a powerful utility used to process and manipulate text in files. It can perform a variety of operations such as searching, find-and-replace, insertion, deletion, and more, without the need to open the file in an editor. This makes it a highly efficient tool for managing and editing text, especially w
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
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
Ccat – Colorize Cat Command Output command in Linux with Examples
ccat is a Linux and macOS cat command that improved its precursor: the syntax highlighted file contents can be displayed with its help. Therefore, in the case of source code and configuration files, it is extremely helpful. It can highlight over 10 languages, like JavaScript, Java, Ruby, Python, Go, C, and JSON. Syntaxccat [OPTIONS] [FILE...]Basic
3 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
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
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
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
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
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
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
lsmod command in Linux with Examples
lsmod command is used to display the status of modules in the Linux kernel. It results in a list of loaded modules. lsmod is a trivial program which nicely formats the contents of the /proc/modules, showing what kernel modules are currently loaded. Syntax: lsmod Example: Run lsmod at the command line to list all active kernel modules. lsmod Output:
1 min read
emacs command in Linux with examples
Introduction to Emacs Editor in Linux/Unix Systems: The Emacs is referred to a family of editors, which means it has many versions or flavors or iterations. The most commonly used version of Emacs editor is GNU Emacs and was created by Richard Stallman. The main difference between text editors like vi, vim, nano, and the Emacs is that is faster, po
5 min read
host command in Linux with examples
host command in Linux system is used for DNS (Domain Name System) lookup operations. In simple words, this command is used to find the IP address of a particular domain name or if you want to find out the domain name of a particular IP address the host command becomes handy. You can also find more specific details of a domain by specifying the corr
2 min read
yes command in Linux with Examples
yes, the command in Linux is used to print a continuous output stream of a given STRING. If STRING is not mentioned then it prints 'y'; Syntax: of `yes` command in Linuxyes [STRING] Note: To stop printing please press Ctrl + C. Use of `yes` commandlet us say that we want to delete all the `.txt` files present in the current directory. Instead of wr
2 min read
bzdiff command in linux with examples
bzdiff command in Linux is used to compare the bzip2 compressed files. Bzcmp and bzdiff are used to invoke the cmp or the diff program on bzip2 compressed files. All options specified are passed directly to cmp or diff. If only one file is specified, then the files compared are file1 and an uncompressed file1.bz2. If two files are specified, then t
1 min read
bzcmp command in Linux with examples
The bzcmp utility is used to invoke the cmp utility on bzip2 compressed files. All options specified are passed directly to cmp. As internally bzcmp calls cmp, We can pass the cmp command options to bzcmp. If only one file is specified, then the files compared are file1 and an uncompressed file1.bz2. If two files are specified, then they are uncomp
2 min read
fold command in Linux with examples
The fold command in Linux wraps each line in an input file to fit a specified width and prints it to the standard output. By default, it wraps lines at a maximum width of 80 columns, which is configurable. To fold input using the fold command pass a file or standard input to the command. Syntax of `fold` command in Linux fold [OPTION] [FILE] We can
3 min read
halt command in Linux with examples
This command in Linux is used to instruct the hardware to stop all the CPU functions. Basically, it reboots or stops the system. If the system is in runlevel 0 or 6 or using the command with --force option, it results in rebooting of the system otherwise it results in shutdown. Syntax: halt [OPTION]... .halt-command-table { border-collapse: collaps
2 min read
groupmod command in Linux with examples
groupmod command in Linux is used to modify or change the existing group on Linux system. It can be handled by superuser or root user. Basically, it modifies a group definition on the system by modifying the right entry in the database of the group. Syntax: groupmod [option] GROUP Files: The groupmod command has following files. /etc/group: Group A
2 min read
vmstat command in Linux with Examples
vmstat command in Linux/Unix is a performance monitoring command of the system as it gives the information about processes, memory, paging, block IO, disk, and CPU scheduling. All these functionalities makes the command vmstat also known as virtual memory statistic reporter. The very first report produced gives the average details since the last re
3 min read
diff3 command in Linux with examples
diff3 command is used to compare the three files line by line. It internally uses the diff command to compare. When three files are compared then the following output may come which have their own meaning: ==== : It means all the files are different. ====1 : File 1 is different. ====2 : File 2 is different. ====3 : File 3 is different. Syntax: diff
3 min read
bzless command in Linux with examples
bzless is a command similar to bzmore, but it has many more features. bzless does not have to read the entire input file before starting, so with a large file, it starts up faster than text editors like vi. bzless uses termcap (or terminfo on some systems), so it can run on a variety of terminals. Similar to bzmore it works on both types of files(c
2 min read
cron command in Linux with Examples
The cron is a software utility, offered by a Linux-like operating system that automates the scheduled task at a predetermined time. It is a daemon process, which runs as a background process and performs the specified operations at the predefined time when a certain event or condition is triggered without the intervention of a user. Dealing with a
4 min read
Article Tags :
three90RightbarBannerImg