Sed - Workflow

来源:互联网 发布:飞天侠淘宝客源码 编辑:程序博客网 时间:2024/06/18 03:59

This chapter will explain how exactly Sed works. To become an expert Sed user, one needs to know its internals. Sed follows a simple workflow: Read, Execute, and Display. The following diagram depicts the workflow.

Sed Workflow

Read

Sed reads a line from the input stream (file, pipe, or stdin) and stores it in its internal buffer called pattern buffer.

Execute

All Sed commands are applied sequentially on the pattern buffer. By default, Sed commands are applied on all lines (globally) unless line addressing is specified.

Display

Sed sends the (modified) contents to the output stream. After sending the data, the pattern buffer will be empty. This process repeats until the file is exhausted.

Examples

Let us create a text file quote.txt to contain a quote of the famous author Paulo Coelho.

[jerry]$ vi quote.txt There is only one thing that makes a dream impossible to achieve: the fear of failure.  - Paulo Coelho, The Alchemist

To understand the workflow of Sed, let us display the contents of the file quote.txt using Sed. This example simulates the cat command.

[jerry]$ sed '' quote.txt

When the above code is executed, it will produce the following result.

There is only one thing that makes a dream impossible to achieve: the fear of failure. 

In the above example, quote.txt is the input file name and before that there is a pair of single quote that implies the Sed command. Let us demystify this operation.

First Sed reads a line from the input file quote.txt and stores it in its pattern buffer. Then it applies Sed commands on the pattern buffer. In our case, no Sed commands are there, hence no operation is performed on the pattern buffer. Finally it deletes and prints the contents of the pattern buffer on the standard output. Isn't it simple?

In the following example, Sed accepts input from the standard input stream.

[jerry]$ sed '' 

When the above code is executed, it prompts us to enter some text from stdin. So let's enter a text line as shown below:

There is only one thing that makes a dream impossible to achieve: the fear of failure. 

After entering the line, when we press enter it produces the following result:

There is only one thing that makes a dream impossible to achieve: the fear of failure.

To exit from the Sed session, press ctrl-D (^D).

0 0
原创粉丝点击