or |) from another command, or to load it directly into "sed". This command works the same as other editors, except that the file is not displayed and visual editing is not allowed. Commands are passed to "sed" to manipulate the stream. There are five basic things you can do with "sed". Of course, "sed" is so powerful and has other advanced features, but you only need to focus on five basic things. Five functional types"/> or |) from another command, or to load it directly into "sed". This command works the same as other editors, except that the file is not displayed and visual editing is not allowed. Commands are passed to "sed" to manipulate the stream. There are five basic things you can do with "sed". Of course, "sed" is so powerful and has other advanced features, but you only need to focus on five basic things. Five functional types">
search
HomeSystem TutorialLINUXIntroduction: Learn how to use sed in the basics of LFCS

Introduction: Learn how to use sed in the basics of LFCS

Jan 09, 2024 am 08:50 AM
linuxlinux tutorialRed Hatlinux systemlinux commandlinux certificationred hat linuxlinux video

Introduction Another useful command for Linux Foundation Certified System Administrators (LFCS) is "sed", which originally stood for "Streaming Editor".

The "sed" command is an editor that can edit files as streams. The way to stream a file is to pipe it (> or |) from another command, or to load it directly into "sed".

This command works the same as other editors, except that the file is not displayed and visual editing is not allowed. Commands are passed to "sed" to manipulate the stream.

You can do five basic things with "sed". Of course, "sed" is so powerful and has other advanced features, but you only need to focus on five basic things. The five function types are as follows:
search
replace
delete
Add to
Change/Transform
Before we dive into the command parameters, we need to look at the basic syntax.

grammar

The syntax of the "sed" command is:

sed [选项] 命令 [要编辑的文件]

These "options" will be covered in the appropriate sections of this article. A "command" can be a regular expression search and replace pattern. Read on to learn how "sed" works and learn basic commands. As I mentioned before, "sed" is a very powerful tool with many more options available that I will cover in this article.

Example file

If you open a terminal, you can create a file for the "sed" example. Execute the following command:

cd ~
grep --help >grephelp.txt

You should now have a file named grephelp.txt in your HOME folder. The contents of this file are help instructions for the grep command.

search

Searching for a specific string is a common function of editors, and performing a search in "sed" is no exception.

Perform a search to find a string in a file. Let's take a look at a basic search.

If we wanted to search for the word PATTERN in the sample file, we would use the following command:

sed -n 's/PATTERN/PATTERN/p' grephelp.txt

Note: If you cut and paste the command, make sure to replace the single quotes with the standard single quotes on your keyboard.

Parameter -n is used to suppress automatic printing of each line (except the line specified with the p command). By default, each line fed into "sed" will be printed to standard output (stdout). If you run the above command without the "-n" option, you will see each line of the original file along with the matching lines.

The file name to search is "grephelp.txt" we created in the "Sample Files" section.

The remaining part is 's/PATTERN/PATTERN/p' . This section is basically divided into four parts. The first part of s specifies to perform a replace, or a search and replace.

The remaining second and third parts are patterns. The first is the pattern to search for, and the last is the pattern to replace the matching string in the stream. In this example, we find the string PATTERN and replace it with PATTERN. By finding and replacing the same string, we don't change the file at all, not even on the screen.

The last command is p. It specifies that a new line is printed after replacement. Of course, since the same string is replaced, nothing changes. Since we suppressed printing lines using the -n parameter, the changed lines will be printed using the p command.

This complete command allows us to perform a search and view matching results.

replace

When searching for a specific string, you may want to replace the new string with the matching string. Replacing a string with another is a very common operation.

We can perform the same search using the following command:

sed -n 's/PATTERN/Pattern/p' grephelp.txt

At this time, the string "PATTERN" changes to "Pattern" and is displayed. If you view the file using the command cat grephelp.txt, you will see that the file has not changed. This change is made only to the output on the screen. You can pipe the output to another file using the following command:

sed 's/PATTERN/Pattern/' grephelp.txt > grephelp1.txt

A new file named grephelp1.txt will now exist with the changed file saved in it. If p is left as the fourth option, the problem is that each line of the replaced string will be repeated twice in the file. We can also remove the "-n" parameter to allow all lines to be printed.

Another way to replace strings with the same string is to use the & symbol to represent the search string. For example, the command s/PATTERN/&/p has the same effect. We can add a string, for example to add S, we can use the command s/PATTERN/&S/p.

What if we want to replace only a certain pattern in each line? You can specify specific occurrences of matches to be replaced. Of course, each row's replacement is a specific number. For example, the example file has a lot of dashes on it. Some lines have at least two dashes, so we can replace the second dash on each line with another character. The command to replace the second dash - with an asterisk * on each line would be:

sed 's/-/*/2' grephelp.txt

Here, we use the original s to perform the replacement. Characters - are replaced with *. 2 means we want to replace the second - on each line if it exists. If we omit command 2, the first occurrence of the dash is replaced. Only the first dash is replaced instead of dashes in every line.

If you want to search and replace all dashes on a line with an asterisk, use the g command:

sed 's/-/*/g' grephelp.txt

Commands can also be combined. Assuming you want to replace the dashes starting from the second occurrence, the command would be:

sed 's/-/*/2g' grephelp.txt

现在从第二个开始出现的破折号将被星号取代。

删除

搜索过程中有很多时候你可能想要完全删除搜索字符串。

例如,如果要从文件中删除所有破折号,你可以使用以下命令:

sed 's/-//g' grephelp.txt

替换字符串为空白,因此匹配的字符串将被删除。

添加

当找到匹配时,你可以添加一行特定的文本,来使这行在浏览或打印中突出。

如果要在匹配后插入新行,那么使用 a 命令,后面跟上新行的字符串。还包括要匹配的字符串。例如,我们可以找到一个 --,并在匹配的行之后添加一行。新行的字符串将是 double dash before this line。

sed '/--/ a "double dash before this line"' grephelp.txt

如果要在包含匹配字符串的行之前加上这行,请使用 i 命令,如下所示:

sed '/--/ i "double dash after this line"' grephelp.txt
改变/变换

如果需要改变/变换一行,则可以使用命令 c。

假设我们有个有一些私人信息的文档,我们需要更改包含特定字符串的行。c 命令将改变整行,而不仅仅是搜索字符串。

假设我们想要阻止示例文件中包含单词 PATTERN 的每一行。更改的行将显示为 This line is Top Secret。命令是:

sed '/PATTERN/ c This line is Top Secret' grephelp.txt

可以进行更改特定字母的大小写的转换。例如,我们可以使用命令 y 将所有小写 a 更改为大写 A,如下所示:

sed 'y/a/A/' grephelp.txt

可以指定多个字母,如 abdg,如下命令所示:

sed 'y/abdg/ABDG/' grephelp.txt

确保第二组字母与第一组字母的顺序相同,否则会被替换和转换。例如,字符串 y/a/D/ 将用大写 D 替换所有小写的 a。

就地更改

如果你确实要更改所使用的文件,请使用 -i 选项。

例如,要将 PATTERN 改为 Pattern,并对文件进行更改,则命令为:

sed -i 's/PATTERN/Pattern/' grephelp.txt

现在文件 grephelp.txt 将被更改。-i 选项可以与上述任何命令一起使用来更改原始文件的内容。

练习这些命令,并确保你理解它们。“sed” 命令非常强大。

(题图:Pixabay,CC0)

The above is the detailed content of Introduction: Learn how to use sed in the basics of LFCS. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Linux就该这么学. If there is any infringement, please contact admin@php.cn delete
What are the main tasks of a Linux system administrator?What are the main tasks of a Linux system administrator?Apr 19, 2025 am 12:23 AM

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

Is it hard to learn Linux?Is it hard to learn Linux?Apr 18, 2025 am 12:23 AM

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy

What is the salary of Linux administrator?What is the salary of Linux administrator?Apr 17, 2025 am 12:24 AM

The average annual salary of Linux administrators is $75,000 to $95,000 in the United States and €40,000 to €60,000 in Europe. To increase salary, you can: 1. Continuously learn new technologies, such as cloud computing and container technology; 2. Accumulate project experience and establish Portfolio; 3. Establish a professional network and expand your network.

What is the main purpose of Linux?What is the main purpose of Linux?Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

Does the internet run on Linux?Does the internet run on Linux?Apr 14, 2025 am 12:03 AM

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

What are Linux operations?What are Linux operations?Apr 13, 2025 am 12:20 AM

The core of the Linux operating system is its command line interface, which can perform various operations through the command line. 1. File and directory operations use ls, cd, mkdir, rm and other commands to manage files and directories. 2. User and permission management ensures system security and resource allocation through useradd, passwd, chmod and other commands. 3. Process management uses ps, kill and other commands to monitor and control system processes. 4. Network operations include ping, ifconfig, ssh and other commands to configure and manage network connections. 5. System monitoring and maintenance use commands such as top, df, du to understand the system's operating status and resource usage.

Boost Productivity with Custom Command Shortcuts Using Linux AliasesBoost Productivity with Custom Command Shortcuts Using Linux AliasesApr 12, 2025 am 11:43 AM

Introduction Linux is a powerful operating system favored by developers, system administrators, and power users due to its flexibility and efficiency. However, frequently using long and complex commands can be tedious and er

What is Linux actually good for?What is Linux actually good for?Apr 12, 2025 am 12:20 AM

Linux is suitable for servers, development environments, and embedded systems. 1. As a server operating system, Linux is stable and efficient, and is often used to deploy high-concurrency applications. 2. As a development environment, Linux provides efficient command line tools and package management systems to improve development efficiency. 3. In embedded systems, Linux is lightweight and customizable, suitable for environments with limited resources.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software