Sed is known as a stream editor, which is useful for working with text files.
In this shot, we will learn about the pattern range in Sed.
A pattern range is used to match the content of a file.
In this example, we will work on a file called data.txt
. This file contains the content of 9
lines, which have already been created for you.
1.Educative is an online learning environment for developers of all levels.2.It uses text-based, interactive courses, which are hand-selected by the learner.3.Educative’s courses cover a variety of topics related to computer science and software development.4.Courses are written either by Educative’s dedicated group of technical content creators or by experienced third-party authors.5.Much of Educative’s content is written by published authors from their well-performing texts, seeking new outlets to share their knowledge.6.Authors are able to upload their own content with the help of a technical and proofreading team, so they have control over how their content is offered.7.Courses come packed with interactive features that are built into Educative’s all-in-one online platform.8.This includes code snippets, playgrounds, quizzes, interactive graphs, and more.9.The Educative platform enables learners to read at their own speed and build real projects without the hassle of extra downloads.
Now, we will try to print the content of the file where the term Educative
is present in the line. Over here, Educative
is the pattern range.
We will use the following command to achieve this:
sed -n '/Educative/ p' data.txt
Where:
-n
is used to suppress the default behavior of the pattern buffer. This means that it will print the pattern buffer automatically. Since we are printing the output with p
, we will suppress the default printing with -n
. If we don’t suppress it, then the output will be printed 2
times.p
is used to print the content./Educative/
is the pattern range and the file we are passing is data.txt
.After executing the command given above, we will print all the lines that satisfy the given pattern range.
sed -n '/Educative/ p' data.txt
We will limit the pattern range to certain lines, using an address.
In the following code snippet, we provide 4
as an address and courses
as a pattern range, which means that the Sed command will print all the lines from the first occurrence of courses
till line 5.
sed -n '/courses/, 4p' data.txt
We can use two patterns to perform operations on the content present between them.
In the following code snippet, we provide it
and Authors
as pattern ranges, which means that the Sed command will print all the lines between them.
sed -n '/It/,/Authors/p' data.txt