首先看下面一段凌乱的Python代码
4. import random
5.
6.
7. def rabinMiller(num):
8. # Returns True if num is a prime number.
9.
10. s = num - 1
11. t = 0
12. while s % 2 == 0:
这是从网上拷贝的一段python代码的开头部分,格式非常混乱,有行号,有过多的空行和空格,这种直接拷贝的代码是无法直接运行的,需要你手动把这些无用的符号删除,对于成百上千行的代码,如果手动删除太多麻烦,即便你使用一些文本编辑器的替换功能,也未必能够很好的达到你的目的。这个时候就是sed大显身手的时候了。
- 删除空白行(对于一个Python代码块,空白行会产生错误)
- 删除行号,使代码左对齐
- 删除备注(以#号开头的行)
sed -e 's/^...//g' -e '/^$/d' -e '/^\s*#/d' -e 's/^.//g' tt.txt
上述代码通过-e参数指定了4条sed命令,分别删除每一行开头的前三个字符(行号)、删除空白行、删除以#号开头的备注行(\s表示空格符)、删除每行第一个字符使左对齐。随后就得到了标准的Python代码格式.
import random
def rabinMiller(num):
s = num - 1
t = 0
while s % 2 == 0:
{}:嵌套sed命令
对于更为复杂的sed命令,可以使用大括号将不同的命令分组,比如还是上面Python代码,如果想把4-100行之间的代码进行整理,则可以先指定行范围,然后使用大括号将不同的sed命令组合起来。
sed -n '
4,100{
s/^...//g
/^$/d
/^\s*#/d
s/^.//g
p
}
`
r:读入文件
这儿需要两个文件做演示,新建另一个文本文件example1.txt,如下
The other test file.
ID 0000124
Test END!
如果我们要在example.txt文件的第二行开始插入该文件exemple1.txt
sed '2r example1.txt' example.txt
# This is a test file.
# It is the last day of 2018.
# The other test file.
# ID 0000124
# Test END!
# Hope all you success!
# HAPPY NEW YEAR!
如果要在example.txt文件的最后一行插入
sed '$r example1.txt' example.txt
如果要在数字8的行后面插入该文件
sed '/8/r example1.txt' example.txt
# This is a test file.
# It is the last day of 2018.
# The other test file.
# ID 0000124
# Test END!
# Hope all you success!
# HAPPY NEW YEAR!
a或i:添加字符串行
比如我们要在example.txt文件的第二行之后(a)或之前(i)添加一行“THIS is the middle of the file”
sed '2a THIS is the middle of the file' example.txt
# This is a test file.
# It is the last day of 2018.
# THIS is the middle of the file
# Hope all you success!
# HAPPY NEW YEAR!
sed '2i THIS is the middle of the file' example.txt
# This is a test file.
# THIS is the middle of the file
# It is the last day of 2018.
# Hope all you success!
# HAPPY NEW YEAR!
a和i都可以完成添加行,不同的是,a(append)是在指定行之后添加,i(insert)是在指定行之前添加。
c:修改行
比如我们要把example.txt文件的第二行修改成“It is the first day of 2019”,可以使用c(change)参数来修改。
sed '2c It is the first day of 2019' example.txt
# This is a test file.
# It is the first day of 2019
# Hope all you success!
# HAPPY NEW YEAR!
“=”:输出行号
之前学过awk,结合”wc -l”,可以输出一个文件的行数。
wc -l example.txt | awk '{print $1}'
# 4
当然更简单的方法是在sed中使用“=”输出行号。用法如下:
sed -n '$=' example.txt
# 4
我们还可以筛选出符合一定条件的行,比如输出以“H”开头行的行号
sed -n '/^H/=' example.txt
# 3
# 4
y:转换字符
比如把所有的“a”转换成“A”:
sed 'y/a/A/' example.txt
# This is A test file.
# It is the lAst dAy of 2018.
# HopeAll you success!
# HAPPY NEW YEAR!
l:显示控制符
在寻找bug的时候特别有用,把一般不显示的文本控制符显示出来。
sed -n 'l' example.txt
# This is a test file.$
# It is the last day of 2018.$
# Hope all you success!$
# HAPPY NEW YEAR!$
在每一行的末尾都加上了“$“,表示该行结束。
百读不如一练
===== THE END ====
参考资料:http://www.grymoire.com/Unix/Sed.html#uh-30