sed工具

来源:互联网 发布:midi软件下载 编辑:程序博客网 时间:2024/06/06 00:39

一、sed的用法
  sed本身是一个管道命令,可以分析standard input的,而且sed还可以进行数据替换、删除、新增、选取特定行等功能。

1.行为单位的新增和删除

  a:新增,a的后面可以接字符串,这些字符串会在新的一行出现
  d:删除,可以指定删除的行,例sed ‘2,5d’
   i:插入,在当前行的上一行插入新的字符,sed ‘2i insert’

[lirong@lr ~/work_lr/mygit/shell/test]# cat -n file.txt      1  first     2  second     3  three     4       5  four     6  five     7  six     8  #[lirong@lr ~/work_lr/mygit/shell/test]# cat -n file.txt | sed '2a add second'     1  first     2  secondadd second     3  three     4       5  four     6  five     7  six     8  #[lirong@lr ~/work_lr/mygit/shell/test]# cat -n file.txt | sed '2,5d'     1  first     6  five     7  six     8  #[lirong@lr ~/work_lr/mygit/shell/test]# cat -n file.txt | sed '2i insert'     1  firstinsert     2  second     3  three     4       5  four     6  five     7  six     8  #

2.行为单位的替换和显示

  c:替换,后面可以接字符串
  n:经过指定的行将会被显示
  s:替换,sed ‘s/要被替换的字符串/新的字符串/g’

[lirong@lr ~/work_lr/mygit/shell/test]# cat -n file.txt | sed '2,5c number'     1  firstnumber     6  five     7  six     8  #[lirong@lr ~/work_lr/mygit/shell/test]# cat -n file.txt | sed -n '5,7p'     5  four     6  five     7  six[lirong@lr ~/work_lr/mygit/shell/test]# cat -n file.txt | sed 's/#/eight/g'     1  first     2  second     3  three     4       5  four     6  five     7  six     8  eight

3.直接修改文件内容

  在上述的情况中,使用了管道,事实上并没有改变文件的内容,sed的”-i”参数可以直接修改文件的内容。下列中将文件内容的#修改为eight。

[lirong@lr ~/work_lr/mygit/shell/test]# nl file.txt      1  first     2  second     3  three     4  four     5  five     6  six     7  #[lirong@lr ~/work_lr/mygit/shell/test]# sed -i 's/#/eight/g' file.txt [lirong@lr ~/work_lr/mygit/shell/test]# nl file.txt      1  first     2  second     3  three     4  four     5  five     6  six     7  eight

2017-11-29-LR 鸟哥的私房菜

原创粉丝点击