Sed技巧篇

来源:互联网 发布:linux误删文件恢复 编辑:程序博客网 时间:2024/05/22 02:23

Sed技巧篇


Table of Contents

  • 1 直接对文件进行编辑
  • 2 使用正则表达式扩展
  • 3 标签
  • 4 文本间隔
  • 5 编号


1 直接对文件进行编辑


使用-i选项可以直接对文件进行编辑,省去了重定向的麻烦。但是注意,这个选项会破坏sed默认不修改源文件的规则,请注意备份。


sed -i [pattern] [file]


实例:


hic@hic-Rev-1-0:~$ cat test.txt        2   System calls (functions provided by the kernel)       3   Library calls (functions within program libraries)       4   Special files (usually found in /dev)       5   File formats and conventions eg /etc/passwd       6   Games       7   Miscellaneous  (including  macro  packages  and  conventions), e.g.           man(7), groff(7)       8   System administration commands (usually only for root)       9   Kernel routines [Non standard]hic@hic-Rev-1-0:~$ sed -i 's/calls/hello/g' test.txt hic@hic-Rev-1-0:~$ cat test.txt        2   System hello (functions provided by the kernel)       3   Library hello (functions within program libraries)       4   Special files (usually found in /dev)       5   File formats and conventions eg /etc/passwd       6   Games       7   Miscellaneous  (including  macro  packages  and  conventions), e.g.           man(7), groff(7)       8   System administration commands (usually only for root)       9   Kernel routines [Non standard]


2 使用正则表达式扩展


使用-r选项,同时对模式加上双引号。


sed -r "pattern" file


实例:


hic@hic-Rev-1-0:~$ TEMP=calls; \> sed -r "s/$TEMP/helloworld/g" test.txt        2   System helloworld (functions provided by the kernel)       3   Library helloworld (functions within program libraries)       4   Special files (usually found in /dev)       5   File formats and conventions eg /etc/passwd       6   Games       7   Miscellaneous  (including  macro  packages  and  conventions), e.g.           man(7), groff(7)       8   System administration commands (usually only for root)       9   Kernel routines [Non standard]


3 标签


b label,无条件跳转到label,如果没有指定,跳转到命令的结尾。


t label,如果最后一次输入的最后一个s///自明零执行成功,跳转到标签label,如果没有指定,则跳转到命令的结尾。


4 文本间隔


1.在每一行后面添加一个空行


sed  Gawk '{printf("%s\n\n",$0)}'


2.将所有的空行删除并在每一行的后面增加一个空行


sed '/^$/d;G'awk '!/^$/{printf("%s\n\n",$0)}'


3.在每一行后面增加两个空行


sed 'G;G'awk '{ptinrf("%s\n\n\n",$0)}'


4.将第一个脚本产生的空行全部删除(删除所有的偶数行)


sed 'n;d'awk '{f=!f;if(f)print $0}'


5.在匹配行之前插入一行


sed '/pattern/G'awk '{if(/pattern/) printf("%s\n\n",$0);else print $0}'


6.在匹配行前后均插入一个空行


sed '/pattern/{x;p;x;G;}'awk '{if(/pattern/) printf("\n%s\n\n",$0); else print $0}'


5 编号


1.为文件的每一行进行编号


sed = filename | sed 'N;s/\n/\t/'awk '{i++;printf("%d\t%s\n",i,$0)}'
  1. 对文件的所有行进行编号(行号在左,文字右端对齐)
sed = filename | sed 'N;s/^/  /; s/ *\(.\{6,\}\)\n/\1 /'awk '{i++;printf("%6d %s\n",i,$0)}'


3.对文件的所有行进行编号,但是仅仅显示非空白行的行号

sed '/./=' filename | sed '/./N; s/\n/ /'awk '{i++;if(!/^$/)printf("%d %s\n",i,$0);else print}'


4.计算行数(模拟wc -l)

sed -n '$#'awk '{i++}END{print i}'




Date: 2012-09-14 五

Author: hic

Org version 7.9.1 with Emacs version 23

Validate XHTML 1.0
原创粉丝点击