sed - 编辑文本文件

it2024-01-05  62

语法

sed [-hnV] [-e <script>] [-f script文件] [文本文件]

     -h:帮助; -n:不显示过程,直接显示处理结果;  -V:显示版本。

     -e <script>:使用script处理文本文件

          a:新增,a的后面可以接字符串,而这些字符串会在新的一行出现;

          c:取代,c的后面可以接字符串,这些字符串可以取代n1,n2之间的行;

          d:删除;

          i:插入,i的后面可以接字符串,而这些字符串会在新的一行出现;

          p:打印,将某个选择的数据输出;

          s:取代,通常可以搭配正则表达式,如1,20s/old/new/g。

     -f <script文件>:使用scropt文件中的内容处理文本文件

    

如:

sed -e 5a\hello file     // 在 file 文件第 5 行后添加一行 hello

nl file | sed '2a hello'     // 在第2行后添加hello

nl file | sed '2i hello \'      // 在第2行前添加hello等多行内容

nl file | sed '5d'     // 删除第 5 行

nl file | sed '3,$d'     // 删除第 3 到最后一行

nl file | sed '2,5c hello'     // 以hello替带2到5行内容

nl file | sed -n '5,7p'

nl file | sed -n '/hello/p'     // 只显示带hello的行

nl file | sed -n '/hello/d'     // 删除带hello的行

nl file | sed -n '/hello/{s/hello/world/;p;q}'     //搜索带hello的行,执行{}内的命令,将hello替换为world,并输入

sed 's/被替换的字符串/新的字符串/g'          //将被替换的字符串替换为新的字符串

/sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g'

/sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g' | sed 's/Bcast.*$//g'

nl file | sed -e '3,$d' -e 's/hello/world'

sed -i 's/\.$/\!/g' file     // 每一行结尾如果是 . ,则将 . 替换为 !

sed -i '$a hello' file     // 在file文件最后一行添加 hello

 

最新回复(0)