Linux Sed Tutorial: 6 Examples of Sed Branching Operations
Like any other programming language, sed also provides special branching commands to control the flow of the program.
In this article, let's review the following two types of Sed branches.
- Sed unconditional branch
- Sed conditional branching
Sed unconditional branch syntax:
$ sed ':label command(s) b label'
- :label - Label specification.
- commands – any sed commands
- label – any name for the label
- blabel - jump to label without checking any conditions. If label is not specified, jump to the end of the script.
Sed conditional branch syntax:
$ sed ':label command(s) t label'
- :label - Label specification.
- commands – any sed commands
- label – any name for the label
- tlabel - Jump to label only if the last substitution command modified the pattern space. If label is not specified, jump to the end of the script.
Creating a sample test file
Let us first create the jiyik_sed.txt file which will be used in the examples mentioned below .
jiyik_sed.txt
Linux Administration Scripting Tips and Tricks Windows Administration Database Administration of Oracle Administration of Mysql Security Network Online\ Security Productivity Google Search\ Tips "Web Based Time Tracking, Web Based Todo list and Reduce Key Stores etc"
Check the file contents as follows
Sed Example of Unconditional Branching
Sed Example 1. Replace the first occurrence of a pattern in the entire file
In the file jiyik_sed.txt, replace the first occurrence of “ Administration ” with “ Supervision ”.
$ sed '/Administration/{
s/Administration/Supervision/
:loop
n
b loop
}' jiyik_sed.txt
Let’s look at the results
- In the above sed command, it simply reads and prints the pattern space line by line until it matches Administration .
- Once Administration is matched , replace Administration with Supervision (only appears once, note there is no "g" flag replacement).
-
Once the first match is replaced, just read the remaining file contents and print them.
-
n
is a sed command that prints the pattern space and overwrites it with the next line. -
Use
loop
as label.n
Print the current line and overwrite the pattern space with the next line.b
The loop jumps to again:loop
. So this loop prints the rest of jiyik_sed.txt .
-
“”
sed Example 2. Delete the data between
the double quotes of the pattern in the entire file
In our example file, “”
there are three lines between.
$ sed -e ':loop
$!{
N
/\n$/!b loop
}
s/"[^"]*"//g' jiyik_sed.txt
See the following running results
-
The above command keep appends all the lines of the file until the end of the file.
- $! – if it is not end of file.
-
N - Append the next line, with the pattern space
\n
separated by - /\n$/!b loop - If this is not the last line of the file, jump to the loop again.
-
Now all the lines will be available in the pattern space separated by newline characters. Replace
“”
all the occurrences of data in between with nothing.
Sed Example 3. Remove HTML tags from a file
For example, I have a file with the following html content
index.html
<html><body> <table border=2><tr><td valign=top align=right>1.</td> <td>Line 1 Column 2</ td> </table> </body></html>
The following sed command removes all html tags from a given file
$ sed '/</{
:loop
s/<[^<]*>//g
/</{
N
b loop
}
}' index.html
See the following running results
- Each time a line containing '<' is found, all HTML tags in that line are first deleted.
- If the pattern space now contains "<", this means a multi-line tag. Now repeat the following loop:
- Join next line
- Remove all HTML tags until there is no single "<"
- When "<" is not present in the pattern space, we print it out and start a new loop.
Sed Example of Conditional Branching
Sed Example 4. If a line ends with a backslash, append the next line to it
Our sample file has two lines ending with a backslash, and now we have to append the next line to it.
$ sed '
:loop
/\\$/N
s/\\\n */ /
t loop' jiyik_sed.txt
See the following running results
-
Checks if the line
(/\\$/)
ends with a backslash , and if so, reads the next line and appends it to the pattern space,\\
replacing the at the end of the line and the number of spaces that follow with a single space. - If the replacement is successful, repeat the above steps. The branch will only be executed if the replacement is successful.
- Conditional branches are mainly used in recursive patterns.
Sed Example 5. comify a numeric string
$ sed '
:loop
s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/
t loop'
12342342342343434
12,342,342,342,343,434
See the results below
- Divide the numbers into two groups.
- The first group is all the numbers up to the last three digits. The last three digits are captured in the second group.
- The two matching groups are then separated by a comma. The same rule is then applied to the line again and again until all the numbers have been grouped into groups of three.
-
For example, in the first iteration it will be
12342342342343,434
-
In the next iteration
12342342342,343,434
, until there are fewer than three digits.
Sed Example 6. Formatting: Replace each leading space in a line with "+"
$ sed '
s/^ */&\n/
:loop
s/^\n//;s/ \n/\n+/
t loop' jiyik_sed.txt
See the following running results
- Separate all leading spaces and other characters of the line with a newline character.
-
Now replace spaces and newlines with
+
and . So, from right to left, spaces will be replaced with+
and newlines will be shifted one character to the left. -
Finally at the beginning of the line
\n
will be there, so delete that new line.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to install GrayLog on centos
Publish Date:2025/04/06 Views:122 Category:OPERATING SYSTEM
-
Installing Graylog on CentOS requires the following steps: 1. Add EPEL and MongoDB repositories: sudo yum install epel-release -y sudo rpm -Uvh https://repo.mongodb.org/yum/redhat/7/mongodb-org/4.4/x86_64/RPMS/mongodb-org-server-4.4.4-1.el7
export command in Linux
Publish Date:2025/04/05 Views:109 Category:OPERATING SYSTEM
-
The Linux terminal has many environment variables that contain necessary information about the system. Also, applications may require some environment variables in order to execute. export This article will use the command to define an envi
tr Command in Linux Bash
Publish Date:2025/04/05 Views:54 Category:OPERATING SYSTEM
-
In Linux, we can use Bash scripts to perform string manipulation such as concatenation, truncation, and finding words in a text. tr This article will explain how to translate or remove characters using command in Linux Bash . tr Using comma
How to Copy Files and Directories Using Linux Terminal
Publish Date:2025/04/05 Views:122 Category:OPERATING SYSTEM
-
cp We can use the and commands in Linux Terminal rsync to copy files and directories. cp The command is generally used to copy files, while rsync the command is generally used to copy directories. Use cp the command to copy files We use com
Obtaining an IPv4 Address on Unix and Linux
Publish Date:2025/04/05 Views:200 Category:OPERATING SYSTEM
-
IP stands for Internet Protocol, which specifies the principles of Internet communications. An Internet Protocol (IP) address is a unique identifier for each device on the Internet, allowing data to be transferred between connected devices.
Changing permissions on folders and directories in Linux/Unix
Publish Date:2025/04/05 Views:79 Category:OPERATING SYSTEM
-
The file permission system is one of the fundamental security elements of the Linux operating system. These features allow us to adjust file permissions and access modes. We provide permissions based on appropriate rights to avoid vulnerabi
How to Delete a User Account in Linux
Publish Date:2025/04/05 Views:149 Category:OPERATING SYSTEM
-
In Linux, we can have multiple user accounts. Sometimes, we may need to remove some users to deny their access to the system. In such cases, we have to delete the user account. We can use userdel command line utilities to delete user accoun
Switching Users in Linux
Publish Date:2025/04/05 Views:158 Category:OPERATING SYSTEM
-
Like any operating system, Linux can have multiple user accounts. Sometimes we may need to use a different user account to access files or run commands that require permissions as root. This article explains how to switch between different
How to Unzip Bzip2 Files in Linux Terminal
Publish Date:2025/04/05 Views:141 Category:OPERATING SYSTEM
-
tar is a command line tool that allows us to create and decompress tar files. It supports most compression programs, such as gzip , lzip , bzip2 , lzma , , lzop , xz and compress . bzip2 Files compressed with end with .tar.bz2 or .tbz2 . We