Table of Contents
Introduction" >Introduction
sed uses parameters
Search and display data
After finding the line matching the pattern eastern, Search /etc/passwd, find the line corresponding to root, and execute There is a set of commands in curly brackets, each command is separated by a semicolon. Here, replace bash with blueshell, and then output this line:
数据的搜寻并替换
多点编辑
直接修改文件内容(危险动作)

Detailed explanation of sed usage

May 28, 2017 am 10:24 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 uses parameters


Detailed explanation of sed usage##

[root@www ~]# sed [-nefr] [动作]
选项与参数:
-n :使用安静(silent)模式。在一般 sed 的用法中,所有来自 STDIN 的数据一般都会被列出到终端上。但如果加上 -n 参数后,则只有经过sed 特殊处理的那一行(或者动作)才会被列出来。
-e :直接在命令列模式上进行 sed 的动作编辑;
-f :直接将 sed 的动作写在一个文件内, -f filename 则可以运行 filename 内的 sed 动作;
-r :sed 的动作支持的是延伸型正规表示法的语法。(默认是基础正规表示法语法)
-i :直接修改读取的文件内容,而不是输出到终端。

动作说明: [n1[,n2]]function
n1, n2 :不见得会存在,一般代表『选择进行动作的行数』,举例来说,如果我的动作是需要在 10 到 20 行之间进行的,则『 10,20[动作行为] 』

function:
a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
d :删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
p :列印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~
s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!
Copy after login

Detailed explanation of sed usage

Add/delete in line units

Change /etc/ The content of passwd is listed and the line number is printed. 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 "drink tea" after the second line (that is, added to the third line) ?‖ words!

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


If it is before the second line

 nl /etc/passwd | sed '2i drink tea'
Copy after login


If you want to add more than two lines, add two lines of words after the second line, such as "Drink tea or ....." With『drink beer?』


##

[root@www ~]# nl /etc/passwd | sed '2a Drink tea or ......\
> drink beer ?'
1 root:x:0:0:root:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
Drink tea or ......
drink beer ?
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
.....(后面省略).....
Copy after login
Detailed explanation of sed usage

Detailed explanation of sed usageYou must use a backslash "\" between each line to add a new line! Therefore, in the above example, we can find that there is \ at the end of the first line.

Replacement and display in line units


How about replacing the contents of lines 2-5 with "No 2-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 select and display certain line numbers in a file.

Search and display data

Search

/etc/passwd lines with the 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
Detailed explanation of sed usage

If root is found, output all lines except , also output matching lines. Detailed explanation of sed usage

When -n is used, 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 other lines output

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 for data and execute the command

After finding the line matching the pattern eastern, Search /etc/passwd, find the line corresponding to root, and execute There is a set of commands in curly brackets, each command is separated by a semicolon. Here, replace bash 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 q is to exit.


数据的搜寻并替换

除了整行的处理模式之外, sed 还可以用行为单位进行部分数据的搜寻并取代。基本上 sed 的搜寻与替代的与 vi 相当的类似!他有点像这样:


sed 's/要被取代的字串/新的字串/g'
Copy after login


 

先观察原始信息,利用 /sbin/ifconfig 查询 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
Copy after login


-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 sed usage. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 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)

How do I use regular expressions (regex) in Linux for pattern matching? How do I use regular expressions (regex) in Linux for pattern matching? Mar 17, 2025 pm 05:25 PM

The article explains how to use regular expressions (regex) in Linux for pattern matching, file searching, and text manipulation, detailing syntax, commands, and tools like grep, sed, and awk.

How do I monitor system performance in Linux using tools like top, htop, and vmstat? How do I monitor system performance in Linux using tools like top, htop, and vmstat? Mar 17, 2025 pm 05:28 PM

The article discusses using top, htop, and vmstat for monitoring Linux system performance, detailing their unique features and customization options for effective system management.

How do I implement two-factor authentication (2FA) for SSH in Linux? How do I implement two-factor authentication (2FA) for SSH in Linux? Mar 17, 2025 pm 05:31 PM

The article provides a guide on setting up two-factor authentication (2FA) for SSH on Linux using Google Authenticator, detailing installation, configuration, and troubleshooting steps. It highlights the security benefits of 2FA, such as enhanced sec

How do I configure SELinux or AppArmor to enhance security in Linux? How do I configure SELinux or AppArmor to enhance security in Linux? Mar 12, 2025 pm 06:59 PM

This article compares SELinux and AppArmor, Linux kernel security modules providing mandatory access control. It details their configuration, highlighting the differences in approach (policy-based vs. profile-based) and potential performance impacts

How do I back up and restore a Linux system? How do I back up and restore a Linux system? Mar 12, 2025 pm 07:01 PM

This article details Linux system backup and restoration methods. It compares full system image backups with incremental backups, discusses optimal backup strategies (regularity, multiple locations, versioning, testing, security, rotation), and da

How do I use sudo to grant elevated privileges to users in Linux? How do I use sudo to grant elevated privileges to users in Linux? Mar 17, 2025 pm 05:32 PM

The article explains how to manage sudo privileges in Linux, including granting, revoking, and best practices for security. Key focus is on editing /etc/sudoers safely and limiting access.Character count: 159

How do I set up a firewall in Linux using firewalld or iptables? How do I set up a firewall in Linux using firewalld or iptables? Mar 12, 2025 pm 06:58 PM

This article compares Linux firewall configuration using firewalld and iptables. Firewalld offers a user-friendly interface for managing zones and services, while iptables provides low-level control via command-line manipulation of the netfilter fra

How do I manage software packages in Linux using package managers (apt, yum, dnf)? How do I manage software packages in Linux using package managers (apt, yum, dnf)? Mar 17, 2025 pm 05:26 PM

Article discusses managing software packages in Linux using apt, yum, and dnf, covering installation, updates, and removals. It compares their functionalities and suitability for different distributions.

See all articles