Sed技巧篇
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 G awk '{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)}'
- 对文件的所有行进行编号(行号在左,文字右端对齐)
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}'