linux sed 实践

EG1
打印20-30行

seq 1 50
head -30 |tail -10 1.txt
sed -n '20,30p' 1.txt
awk 'NR>10&&NR<20' 1.TXT
grep
-B 显示匹配行之前N
-A 后N
-C 前后各N行
[root@zat sh]# grep 25 -C 2 1.txt
23
24
25
26
27
[root@zat sh]# grep 25 -A 2 1.txt
25
26
27
[root@zat sh]# grep 25 -B 2 1.txt
23
24
25
替换#分隔符可用/@
-i 修改内容
-e 允许多行编辑
[root@zat sh]# sed 's#25#nihao#g' 1.txt
查找文件名字 替换内容
find sh -type f -name "*.txt" | xargs sed -i 's#44# nihao #g'
删除空行
[james@zat sh]$ grep '^$' 2.txt
[james@zat sh]$ grep -v '^$' 2.txt
[james@zat sh]$ sed '/^$/d' 2.txt
[james@zat sh]$ awk /^[^$]/ 2.txt
增加
[james@zat sh]$ sed '2a 99,bbb,zz' 3.txt
1,zhan,cto
2,wang,ceo
99,bbb,zz
3,li,cfo
替换#分隔符可用/@[james@zat sh]$ sed '2i 99,bbb,zz' 3.txt
1,zhan,cto
99,bbb,zz
2,wang,ceo
多行插入
[james@zat sh]$ sed '5i niheo\nkkni\nwokan' 3.txt
1,zhan,cto
2,wang,ceo
3,li,cfo
4,zhao,cxo
niheo
kkni
wokan
5 wu zzz
多行处理

删除
[james@zat sh]$ sed '7,9d' 3.txt
1,zhan,cto
2,wang,ceo
3,li,cfo
4,zhao,cxo
5 wu zzz
6 zai ooo
文本替换s g -i 修改文件内容
[james@zat sh]$ sed 's#zhan#emmmm#g' 3.txt
1,emmmm,cto
2,wang,ceo
[james@zat sh]$ sed -i 's#zhan#emmmm#g' 3.txt
[james@zat sh]$ cat 3.txt
1,emmmm,cto
2,wang,ceo
制定行修改配置
[james@zat sh]$ sed '4s#z#ff#' 3.txt
1,zhanzhan,cto
2,wang,ceo
3,li,cfo
4,ffhao,cxo
分组替换
\(\)和\1
[james@zat sh]$ touch syr_9876_{1..5}_finsh.jpg

-rw-rw-r-- 1 james james 0 4月 18 11:09 syr_9876_1_finsh.jpg
-rw-rw-r-- 1 james james 0 4月 18 11:09 syr_9876_2_finsh.jpg
-rw-rw-r-- 1 james james 0 4月 18 11:09 syr_9876_3_finsh.jpg
-rw-rw-r-- 1 james james 0 4月 18 11:09 syr_9876_4_finsh.jpg
-rw-rw-r-- 1 james james 0 4月 18 11:09 syr_9876_5_finsh.jpg
[james@zat sh]$ ls *jpg | sed -r 's#(^.*)_finish.*#mv & \1.jpg#g'
syr_9876_1_finsh.jpg
syr_9876_2_finsh.jpg
syr_9876_3_finsh.jpg
syr_9876_4_finsh.jpg
syr_9876_5_finsh.jpg
执行
[james@zat sh]$ ls *jpg | sed -r 's#(^.*)_finish.*#mv & \1.jpg#g'|bash
查p
[james@zat sh]$ sed -n '2p' 3.txt
1,zhanzhan,cto

 

posted @ 2018-04-18 16:12  青青子衿zz  阅读(33)  评论(0)    收藏  举报