Linux三剑客之awk,sed,grep

正则表达式全集:http://tool.oschina.net/uploads/apidocs/jquery/regexp.html

[TOC]

Sed

参考:https://www.cnblogs.com/ctaixw/p/5860221.html

sed提取文件中的指定内容

假如有这样一个文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@rac1 tmp]# cat 123
[green]
192.168.1.1

[bule]
192.168.1.123
192.168.1.156

[red]
192.168.1.14
192.168.1.231
192.168.14.27

[yellow]
192.168.2.55
192.168.13.23

想要提取red组的IP

1
sed -n '/red/,/^$/p' | sed -e 's/\[red\]//' -e '/^$/d'

sed递归替换

1
find . -type f|xargs -0 sed -i "s/x/y/g"

sed文件的最后一行和第一行后添加内容

1
2
3
sed -i '$a\hahahaha' file.txt

sed -i '1a\hahahahah' file.txt

sed在某行的前一行或者后一行添加内容

在某行的前一行或后一行添加内容

具休操作如下:

1
2
3
4
#匹配行前加
sed -i '/allow 361way.com/iallow www.361way.com' the.conf.file
#匹配行前后
sed -i '/allow 361way.com/aallow www.361way.com' the.conf.file

而在书写的时候为便与区分,往往会在i和a前面加一个反加一个反斜扛 。代码就变成了:

1
2
sed -i '/2222222222/a\3333333333' test.txt
sed -i '/2222222222/i\3333333333' test.txt

这就就可以很方便的看出要在某一行前或某一行后加入什么内容 。不过经常我记不住a 、i 那个是前那个是后。我的记法是a = after ,i = in front 。这样就知道 i 是前,a 是后了。不过官方的man文件里不是这样解释的,man文件里是这样解释的:

1
2
3
4
a
text Append text, which has each embedded newline preceded by a backslash.
i
text Insert text, which has each embedded newline preceded by a backslash.

而且其可以配合find查找的内容处理,如下:

1
2
find . -name server.xml|xargs sed -i '/directory/i       <!--'
find . -name server.xml|xargs sed -i '/pattern="%h/a -->'

在某行(指具体行号)前或后加一行内容

这里指定的行号是第四行

1
2
sed -i 'N;4addpdf' a.txt
sed -i 'N;4ieepdf' a.txt

sed在指定字符前后添加内容

假设文档内容如下:

1
2
3
4
5
6
7
8
9
[root@localhost ~]# cat /tmp/input.txt

null

000011112222



test

要求:在1111之前添加AAA,方法如下:

sed -i ‘s/指定的字符/要插入的字符&/‘ 文件

1
2
3
4
5
6
7
8
9
10
11
[root@localhost ~]# sed -i  's/1111/AAA&/' /tmp/input.txt                     

[root@localhost ~]# cat /tmp/input.txt

null

0000AAA11112222



test

要求:在1111之后添加BBB,方法如下:

sed -i ‘s/指定的字符/&要插入的字符/‘ 文件

1
2
3
4
5
6
7
8
9
10
11
[root@localhost ~]# sed -i  's/1111/&BBB/' /tmp/input.txt    

[root@localhost ~]# cat /tmp/input.txt

null

0000AAA1111BBB2222



test

要求:(1) 删除所有空行;(2) 一行中,如果包含”1111”,则在”1111”前面插入”AAA”,在”11111”后面插入”BBB”

1
2
3
4
5
6
7
[root@localhost ~]# sed '/^$/d;s/1111/AAA&/;s/1111/&BBB/' /tmp/input.txt   

null

0000BBB1111AAA2222

test

要求:在每行的头添加字符,比如”HEAD”,命令如下:

1
2
3
4
5
6
7
8
9
10
11
[root@localhost ~]# sed -i 's/^/HEAD&/' /tmp/input.txt 

[root@localhost ~]# cat /tmp/input.txt

HEADnull

HEAD000011112222

HEAD

HEADtest

要求:在每行的尾部添加字符,比如”tail”,命令如下:

1
2
3
4
5
6
7
8
9
10
11
[root@localhost ~]# sed -i 's/$/&tail/' /tmp/input.txt      

[root@localhost ~]# cat /tmp/input.txt

HEADnulltail

HEAD000011112222tail

HEADtail

HEADtesttail

说明:
1.”^”代表行首,”$”代表行尾
2.’s/$/&tail/g’中的字符g代表每行出现的字符全部替换,如果想在特定字符处添加,g就有用了,否则只会替换每行第一个,而不继续往后找。

--------------------本文结束,感谢您的阅读--------------------

本文标题:Linux三剑客之awk,sed,grep

文章作者:弓昭

发布时间:2019年05月30日 - 22:07

最后更新:2020年04月08日 - 22:20

原始链接:https://gongzhao1.gitee.io/Linux三剑客之awk-sed-grep/

联系邮箱:gongzhao1@foxmail.com