sed参数
- -n:不打印全文内容
- -i:修改原始文件
- -r:支持扩展正则表达式
Example
num | 终端命令 | 语意 |
---|---|---|
1 | sed -n ‘3p’ /etc/passwd | 打印第3行 |
2 | sed -n ‘1,3p’ /etc/passwd | 打印第1至3行 |
3 | sed -n ‘1~2p’ /etc/passwd | 打印第1开始步长为2的行 |
4 | sed -n ‘1,+2p’ /etc/passwd | 打印第一行和后2行 |
5 | sed -n ‘/^root/p’ /etc/passwd | 打印正则过滤root开头 |
6 | sed -nr ‘/[0-9]{3}/p’ /etc/passwd | 打印三个数字的行 |
p:print
num | 终端命令 | 语意 |
---|---|---|
1 | sed ‘/IPADDR/p’ /etc/sysconfig/network-script/ifcg-eth0 | 打印网络地址信息 |
2 | free | sed -n ‘/Mem/p’ | 过滤内存信息 |
3 | sed -n ‘//$/p’ | 打印第1开始步长为2的行 |
4 | df -h |sed -n ‘1,+2p’ /etc/passwd | 过滤磁盘根分区 |
5 | sed -n ‘/2p;3p,10p/p’ /etc/passwd | 打印多行 |
6 | sed -nr ‘/2!/p’ /etc/passwd | 打印三个数字的行 |
d:delete
num | 终端命令 | 语意 |
---|---|---|
1 | sed -i ‘d’ ./rubbish.txt | 删除文件 |
2 | sed -i '1,3d’ /tmp/* | 删除文件 |
3 | sed -i ‘/dev/!d’ | 不包含dev的行都删除 |
4 | df -h |sed -i '/^#/d /etc/passwd | 删除以#开头的行 |
5 | sed -i ‘/^$/d’ /etc/passwd | 删除空白行 |
c:replace
num | 终端命令 | 语意 |
---|---|---|
1 | sed ‘c 123456’ /etc/sysconfig/network-script/ifcg-eth0 | 所有行都换成123456 |
2 | sed ‘/IPADDR/c IPADDR=192.168.1.3’ | 替换网卡信息 |
3 | sed ‘/127/c 127.0.0.1’ /tmp/ipaddress.txt | 替换127这行为127.0.0.1 |
4 | sed ‘/4c XXXX’ /tmp/ipaddress.txt | 替换第4行为XXXX |
s:substution
num | 终端命令 | 语意 |
---|---|---|
1 | sed ‘s/1024/2048/’ ./tmp/test.txt | 替换每一行第1个出现 |
2 | sed ‘s/1024/2048/g’ ./tmp/test.txt | 替换每一行的全部 |
3 | sed ‘s/1024/2048/2’ ./tmp/test.txt | 替换每一行第2个出现 |
4 | sed ‘s/1024/($)/g’ ./tmp/test.txt | 替换每一行1024为(1024) |
5 | sed ‘2s/1024/2048/g’ ./tmp/test.txt | 替换第2行的全部 |
6 | sed ‘2s/1024//g’ ./tmp/test.txt | 第2行的1024删除掉 |
7 | sed -n ‘2s/1024/2048/p’ ./tmp/test.txt | 替换完成后打印第2行 |
8 | sed ‘s#1024#2048#g’ ./tmp/test.txt | 替换符改为# |
9 | sed ‘s!1024!2048!2’ ./tmp/test.txt | 替换符改为! |
10 | sed ‘s2\10242\20482\2’ ./tmp/test.txt | 替换符改为2,但是要加\ |
11 | echo “123456” | sed -r ‘s/^(.)(.*)(.)$/\3\2\1/’ | 正则符号()具有保留的功能 |
=:打印行号
num | 终端命令 | 语意 |
---|---|---|
1 | sed -n ‘8=’ /etc/passwd | 打印第8行行号 |
2 | sed -n ‘/root/=’ /etc/passwd | 打印有root行的行号 |
3 | sed -n ‘$=’ /etc/passwd | 统计行数 |
3 | wc -l /etc/passwd | 统计行数 |
i:insert
num | 终端命令 | 语意 |
---|---|---|
1 | sed ‘2i ABC_123’ /etc/passwd | 插入到第二行之前 |
2 | sed ‘/1024/i ABC\n2048’ /etc/passwd | 插入到每一个匹配则前 |
a:append
num | 终端命令 | 语意 |
---|---|---|
1 | sed ‘2a ABC_123’ /etc/passwd | 追加到第二行之后 |
2 | sed ‘/1024/a ABC\n2048’ /etc/passwd | 追加到每一个匹配则后 |
r:read
num | 终端命令 | 语意 |
---|---|---|
1 | sed ‘2r ,/cont.txt’ ./dest.txt | 读取cont.txt追加到des.txt第2行 |
2 | sed ‘/1024/r ,/cont.txt’ ./dest.txt | ’ /etc/passwd |
w:write
num | 终端命令 | 语意 |
---|---|---|
1 | sed ‘w ,/cont.txt’ ./dest.txt | 另存dest.txt 为/cont.txt |
2 | sed ‘2,3w ,/cont.txt’ ./dest.txt ’ | 另存dest.txt 的2,3行为/cont.txt |
3 | sed ‘/1024/w ,/cont.txt’ ./dest.txt ’ | 另存dest.txt 的匹配行为/cont.txt |