Table of Contents
Introduction" >Introduction
sed usage parameters
Add/Delete in line units
Just delete the 2nd line
To delete the 3rd to the last line
Add " after the second line (that is, add it to the third line) new line text?』 words!
in line units
replace the contents of lines 2-5 with "No 2- What about "5 number"?
Only list lines 5-7 in the /etc/passwd file
Search and display data
Search/etc/passwd for lines with root keyword" >Search/etc/passwd for lines with root keyword
Search and delete data
Search and execute commands for data
Search and replace data
将 IP 前面的部分予以删除
将 IP 后面的部分予以删除
多点编辑
直接修改文件内容(危险动作)
Home Operation and Maintenance Linux Operation and Maintenance Detailed explanation of sample code sharing for sed command in Linux

Detailed explanation of sample code sharing for sed command in Linux

Jun 07, 2017 am 10:26 AM

Introduction

sed is an online editor that processes content one line at a time. During processing, the currently processed line is stored in a temporary buffer, called "pattern space", and then the sed command is used to process the contents of the buffer. After the processing is completed, the contents of the buffer are sent to the screen. Then process the next line, and repeat until the end of the file. The file contents are not changed unless you use redirection to store the output. Sed is mainly used to automatically edit one or more files; simplify repeated operations on files; write conversion programs, etc.

sed usage parameters

[root@www ~]# sed [-nefr] [动作]
Copy after login

Options and parameters:

-n: Use silent mode. In normal sed usage, all data coming from STDIN is usually listed to the terminal. But if the -n parameter is added, only the line (or action) that has been specially processed by sed will be listed.

-e: Edit sed actions directly in command line mode;

-f: Directly write sed actions in a file, -f file name, you can run the sed action in filename;

-r: The sed action supports the extended regular notation syntax. (Default is basic regular notation syntax)

-i: Directly modify the content of the read file instead of outputting it to the terminal.

Action description: [n1[,n2]]function

n1, n2: may not exist, generally represents "select the number of lines for action", for example, if my The action needs to be performed between 10 and 20 lines, then 『10,20[actionbehavior]』

function:

a:New , a can be followed by strings, and these strings will appear on a new line (the current next line)~

c: instead, c can be followed by strings, and these strings Can replace the lines between n1 and n2!

d: Delete, because it is deletion, so d is usually not followed by any dong dong;

i: Insert, i can be followed by a string, and These strings will appear on a new line (the current previous line);

p: Print, that is, print out a selected data. Usually p will be run together with the parameter sed -n~

s: replacement, you can directly perform the replacement work! Usually this s action can be paired with regular notation! For example, 1,20s/old/new/g That’s it!

Add/Delete in line units

List the contents of /etc/passwd and print the line number. At the same time, please delete lines 2~5!

[root@www ~]# nl /etc/passwd | sed '2,5d'
1 root:x:0:0:root:/root:/bin/bash
6 sync:x:5:0:sync:/sbin:/bin/sync
7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
.....(后面省略).....
Copy after login

The action of sed is '2,5d', that d is delete! Because he deleted lines 2-5, the displayed data does not include lines 2-5~ In addition, please note that originally you should have issued sed -e, but it will work without -e! At the same time, it should also be noted that the actions that follow sed must be enclosed in two single quotes ''!

Just delete the 2nd line

nl /etc/passwd | sed '2d'
Copy after login

To delete the 3rd to the last line

nl /etc/passwd | sed '3,$d'
Copy after login

Add " after the second line (that is, add it to the third line) new line text?』 words!

[root@www ~]# nl /etc/passwd | sed '2a new line text'
1 root:x:0:0:root:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
new line text
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
.....(后面省略).....
Copy after login

If you want to replace and display the contents of lines 2-5 before the second line

nl /etc/passwd | sed '2i new line text'
Copy after login

in line units

replace the contents of lines 2-5 with "No 2- What about "5 number"?

[root@www ~]# nl /etc/passwd | sed '2,5c No 2-5 number'
1 root:x:0:0:root:/root:/bin/bash
No 2-5 number
6 sync:x:5:0:sync:/sbin:/bin/sync
.....(后面省略).....
Copy after login

Through this method we can replace the entire row of data!

Only list lines 5-7 in the /etc/passwd file

[root@www ~]# nl /etc/passwd | sed -n '5,7p'
5 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
6 sync:x:5:0:sync:/sbin:/bin/sync
7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
Copy after login

You can use the line-by-line display function of sed to list a certain line in a certain file. Select some line numbers to display.

Search and display data

Search/etc/passwd for lines with root keyword

nl /etc/passwd | sed '/root/p'
1  root:x:0:0:root:/root:/bin/bash
1  root:x:0:0:root:/root:/bin/bash
2  daemon:x:1:1:daemon:/usr/sbin:/bin/sh
3  bin:x:2:2:bin:/bin:/bin/sh
4  sys:x:3:3:sys:/dev:/bin/sh
5  sync:x:4:65534:sync:/bin:/bin/sync
....下面忽略
Copy after login

If root is found, except output all lines, Matching lines are also output.

When using -n, only the lines containing the template will be printed.

nl /etc/passwd | sed -n '/root/p'
1  root:x:0:0:root:/root:/bin/bash
Copy after login

Search and delete data

Delete all lines containing root in /etc/passwd, and output other lines

nl /etc/passwd | sed  '/root/d'
2  daemon:x:1:1:daemon:/usr/sbin:/bin/sh
3  bin:x:2:2:bin:/bin:/bin/sh
....下面忽略
#第一行的匹配root已经删除了
Copy after login

Search and execute commands for data

After finding the line matching the pattern eastern,

Search /etc/passwd, find the line corresponding to root, and execute the following set of commands in curly brackets. Each command is separated by a semicolon. Here, bash Replace it with blueshell, and then output this line:

 nl /etc/passwd | sed -n '/root/{s/bash/blueshell/;p}'
 1  root:x:0:0:root:/root:/bin/blueshell
Copy after login

If you only replace the first bash keyword of /etc/passwd with blueshell, Exit

nl /etc/passwd | sed -n '/bash/{s/bash/blueshell/;p;q}'    
1  root:x:0:0:root:/root:/bin/blueshell
Copy after login

The last one q means exit.

Search and replace data

In addition to the entire line processing mode, sed can also search and replace partial data in behavioral units. Basically sed's searches and substitutions are quite similar to those of vi! It's a bit like this:

sed 's/string to be replaced/new string/g'

First observe the original information and use /sbin/ifconfig Query IP

[root@www ~]# /sbin/ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:90:CC:A6:34:84
inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::290:ccff:fea6:3484/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
.....(以下省略).....
Copy after login

本机的ip是192.168.1.100。

将 IP 前面的部分予以删除

[root@www ~]# /sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g'
192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
Copy after login

接下来则是删除后续的部分,亦即: 192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0

将 IP 后面的部分予以删除

[root@www ~]# /sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g' | sed 's/Bcast.*$//g'
192.168.1.100
Copy after login

多点编辑

一条sed命令,删除/etc/passwd第三行到末尾的数据,并把bash替换为blueshell

nl /etc/passwd | sed -e '3,$d' -e 's/bash/blueshell/'

1 root:x:0:0:root:/root:/bin/blueshell

2 daemon:x:1:1:daemon:/usr/sbin:/bin/sh

-e表示多点编辑,第一个编辑命令删除/etc/passwd第三行到末尾的数据,第二条命令搜索bash替换为blueshell。

直接修改文件内容(危险动作)

sed 可以直接修改文件的内容,不必使用管道命令或数据流重导向! 不过,由於这个动作会直接修改到原始的文件,所以请你千万不要随便拿系统配置来测试! 我们还是使用下载的 regular_express.txt 文件来测试看看吧!

利用 sed 将 regular_express.txt 内每一行结尾若为 . 则换成 !

[root@www ~]# sed -i 's/\.$/\!/g' regular_express.txt
Copy after login

利用 sed 直接在 regular_express.txt 最后一行加入『# This is a test』

[root@www ~]# sed -i '$a # This is a test' regular_express.txt
Copy after login

由于 $ 代表的是最后一行,而 a 的动作是新增,因此该文件最后新增『# This is a test』!

sed 的『 -i 』选项可以直接修改文件内容,这功能非常有帮助!举例来说,如果你有一个 100 万行的文件,你要在第 100 行加某些文字,此时使用 vim 可能会疯掉!因为文件太大了!那怎办?就利用 sed 啊!透过 sed 直接修改/取代的功能,你甚至不需要使用 vim 去修订!

The above is the detailed content of Detailed explanation of sample code sharing for sed command in Linux. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

deepseek web version entrance deepseek official website entrance deepseek web version entrance deepseek official website entrance Feb 19, 2025 pm 04:54 PM

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

How to install deepseek How to install deepseek Feb 19, 2025 pm 05:48 PM

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

BITGet official website installation (2025 beginner's guide) BITGet official website installation (2025 beginner's guide) Feb 21, 2025 pm 08:42 PM

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

Get the gate.io installation package for free Get the gate.io installation package for free Feb 21, 2025 pm 08:21 PM

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.

Ouyi okx installation package is directly included Ouyi okx installation package is directly included Feb 21, 2025 pm 08:00 PM

Ouyi OKX, the world's leading digital asset exchange, has now launched an official installation package to provide a safe and convenient trading experience. The OKX installation package of Ouyi does not need to be accessed through a browser. It can directly install independent applications on the device, creating a stable and efficient trading platform for users. The installation process is simple and easy to understand. Users only need to download the latest version of the installation package and follow the prompts to complete the installation step by step.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Ouyi Exchange Download Official Portal Ouyi Exchange Download Official Portal Feb 21, 2025 pm 07:51 PM

Ouyi, also known as OKX, is a world-leading cryptocurrency trading platform. The article provides a download portal for Ouyi's official installation package, which facilitates users to install Ouyi client on different devices. This installation package supports Windows, Mac, Android and iOS systems. Users can choose the corresponding version to download according to their device type. After the installation is completed, users can register or log in to the Ouyi account, start trading cryptocurrencies and enjoy other services provided by the platform.

See all articles