标签:pac new root 运行 文本处理 txt begin plain white
1、命令格式和參数
sed [-nefr] [动作] 文件
參数:
-n 安静模式。在sed处理的时候。全部来自STDIN的数据都会被输出到终端。加上-n会仅仅输出处理的哪行
-e 直接在命令列上进行sed动作编辑
-f 直接将sed的动作写在文件内
-r sed动作支持延伸的正则表达(默认仅仅是基础正则)
-i 直接改动文件内容(慎用,尤其是用系统文件做练习的时候)
动作:
a append:添加。在当前行的下一行添加
c :代替,代替n1到n2之间的行
d delete:删除
i 插入,眼下行的上一行插入
p 打印。经常与-n使用
s 代替,s/old/new/g
2、基础使用方法具体解释
(1)第一行之后加入一行
[root@localhost ~]# nl file.txt | sed "1a add text" 1 wtmp begins Mon Feb 24 14:26:08 2014 add text 2 192.168.0.1 3 162.12.0.123 4 this is the last line(2)第一行之前加入一行
[root@localhost ~]# nl file.txt | sed "1i add text" add text 1 wtmp begins Mon Feb 24 14:26:08 2014 2 192.168.0.1 3 162.12.0.123 4 this is the last line(3)删除第2,3行
[root@localhost ~]# nl file.txt | sed "2,3d" 1 wtmp begins Mon Feb 24 14:26:08 2014 4 this is the last line(4)打印第2,3行
[root@localhost ~]# sed -n "2,3p" file.txt 192.168.0.1 162.12.0.123
[root@localhost ~]# sed "2,3p" file.txt wtmp begins Mon Feb 24 14:26:08 2014 192.168.0.1 192.168.0.1 162.12.0.123 162.12.0.123 this is the last line
[root@localhost ~]# cat file.txt wtmp begins Mon Feb 24 14:26:08 2014 192.168.0.1 162.12.0.123 this is the last line处理后
[root@localhost ~]# sed "s/168/169/g" file.txt wtmp begins Mon Feb 24 14:26:08 2014 192.169.0.1 162.12.0.123 this is the last line
[root@localhost ~]# nl file.txt | sed "2afirst\nsecond" file.txt wtmp begins Mon Feb 24 14:26:08 2014 192.168.0.1 first second 162.12.0.123 this is the last line
[root@localhost ~]# nl file.txt | sed "/begin/d" 2 192.168.0.1 3 162.12.0.123 4 this is the last line匹配123,而且把含有123的行162都替换成172
[root@localhost ~]# nl file.txt | sed "/123/{s/162/172/g;q}" 1 wtmp begins Mon Feb 24 14:26:08 2014 2 192.168.0.1 3 172.12.0.123 4 this is the last line这里大括号{}里能够运行多个命令,用;隔开就可以,q是退出
<pre name="code" class="plain">[root@localhost ~]# nl file.txt | sed -e "2d" -e "s/last/new/" 1 wtmp begins Mon Feb 24 14:26:08 2014 3 162.12.0.123 4 this is the new line
[root@localhost ~]# sed -i "/begin/{s/24/25/g}" file.txt [root@localhost ~]# cat file.txt wtmp begins Mon Feb 25 14:26:08 2014 192.168.0.1 162.12.0.123 this is the last line
[root@localhost ~]# sed ‘:a;N;$!ba;s/\n/ /g‘ file.txt wtmp begins Mon Feb 25 14:26:08 2014 192.168.0.1 162.12.0.123 this is the last line
另外一种方式
[root@localhost ~]# tr "\n" " " < file.txt wtmp begins Mon Feb 25 14:26:08 2014 192.168.0.1 162.12.0.123 this is the last line last linen
Linux Sed命令具体解释+怎样替换换行符"\n"(非常多面试问道)
标签:pac new root 运行 文本处理 txt begin plain white
原文地址:http://www.cnblogs.com/yutingliuyl/p/6784447.html