Home System Tutorial LINUX Introduction: 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
linux linux tutorial Red Hat linux system linux command linux certification red hat linux linux 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 [选项] 命令 [要编辑的文件]
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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

删除

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

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

sed 's/-//g' grephelp.txt
Copy after login

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

添加

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

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

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

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

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

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

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

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

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

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

sed 'y/a/A/' grephelp.txt
Copy after login

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

sed 'y/abdg/ABDG/' grephelp.txt
Copy after login

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

就地更改

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

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

sed -i 's/PATTERN/Pattern/' grephelp.txt
Copy after login

现在文件 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to switch Chinese mode with vscode How to switch Chinese mode with vscode Apr 15, 2025 pm 11:39 PM

VS Code To switch Chinese mode: Open the settings interface (Windows/Linux: Ctrl, macOS: Cmd,) Search for "Editor: Language" settings Select "Chinese" in the drop-down menu Save settings and restart VS Code

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

See all articles