Linux sed命令 郝伟 2020/01/15 [TOC]

1. 简介

Linux命令 sed 是专门用于处理文本流的工具,用于对输入流执行基本的文本转换(文件或管道中的输入)。 虽然在某种程度上类似于允许脚本编辑的编辑器,sed只能通过一次输入来工作,因此效率更高。 但这是sed的在管道中过滤文本的能力,这使其与其他类型的编辑器特别有区别。

2. 语法

语法结构

sed [OPTION]... {script-only-if-no-other-script} [input-file]...

常用表达式实际上就以下两种:

# 直接执行命令
sed [-n] [-e] 'command(s)' files 

# 从脚本中执行命令
sed [-n] -f scriptfile files

实际上sed就是实现了文本的“增删改插”,这里的“插”表示在指定位置插入字符串内容: -a: 增, a后接字串,用于插入; -d: 删除,d 后面通常不接任何内容; -c: 替换, c 后面接字串,用于取代 n1,n2 之间内容; -i: 插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);

-p: 打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~ -s: 取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!

-n: 只显示匹配的内容, sed -n '' quote.txt does not show any output:

-e : Next argument is an editing command. Here, angular brackets imply mandatory parameter. By using this option, we can specify multiple commands. Let us print each line twice sed -e '' -e 'p' quote.txt.

3. 示例

3.1. 示例1:删除包含 root@server00 的行

$ sed -i '/root@server00/d' ~/.ssh/authorized_keys

3.2. 示例2:将 root@server00 替换为 root@server01

$ sed -i 's/root@server00/root@server01/g' authorized_keys

3.3. 示例3:在文件的指定行后追加行

# 在testfile文件的第四行后添加一行,并将结果输出到标准输出,在命令行提示符下输入如下命令:
sed -e 4a\newLine testfile

3.4. 示例4:删除指定行

# 删除第2行
sed '2d'

# 删除第2-5行
sed '2,5d'

# 删除第2行至最后一行
sed '2,$d'

# 删除books.txt的第1,2,5行
sed -e '1d' -e '2d' -e '5d' books.txt 

# 删除包含 root 的行
sed  '/root/d'

3.5. 示例5:替换

# 将第2-5行的内容替换为 hello 
sed '2,5c hello'

3.6. 示例6:查询

# 搜索 /etc/passwd有root关键字的行
sed -n '/root/p'

results matching ""

    No results matching ""