linux&github

linux sed 总结

2019-02-15  本文已影响53人  hiekay

1.简介

sed是一种行编辑器,它一次处理一行内容。

2.sed调用方式

sed [options] 'command' file(s)
sed [options] -f scriptfile file(s)

第一种直接在命令行中执行,第二种把命令写到了脚本中,二者无本质区别。

sed -n p hello.txt

说明:
-n:sed会在处理一行文本前,将待处理的文本打印出来,-n参数关闭了这个功能
p:命令表示打印当前行
hello.txt:待处理的文件
这个指令相当于cat

3.定址

告诉sed你期望处理的行,由逗号分隔的两个数字表示,$符号表示最后一行;
当然也可以使用正则来定位期望处理的行。

sed -n '2,$'p hello.txt
sed -n '/100/'p hello.txt 

4.基本命令

hello.txt的内容为

1 2 3
10 20 30
100 200 300
sed '/100/'a\ "new line" hello.txt

输出内容为:

1 2 3
10 20 30
100 200 300
new line
sed '/100/'i\ "new line" hello.txt

输出内容为:

1 2 3
10 20 30
new line
100 200 300
sed '/100/'c\ "new line" hello.txt

输出内容为:

1 2 3
10 20 30
new line
sed '/100/'d hello.txt

输出内容为:

1 2 3
10 20 30
sed 's/100/hello/g' hello.txt 

输出内容为:

1 2 3
10 20 30
hello 200 300

5.元字符集

^:匹配一行的开始
$:匹配一行的结束
.:匹配某个字符
[abc]:匹配指定范围字符

6.实用命令

匹配以10开头的行,并替换为yes,并输出

sed -n 's/^10/yes/p' hello.txt

输出内容为:

yes 20 30
yes0 200 300

取出文件中行手的行号与冒号
设hello.txt的内容为

1:#!/bin/sh
2:cat hello.txt
3:exit

命令:

sed -n -e 's/^[0-9]\{1,\}://g'p hello.txt

输出结果为:

#!/bin/sh
cat hello.txt
exit
上一篇 下一篇

猜你喜欢

热点阅读