Shell 命令 Sed

Shell Sed 命令使用详解

总结

常见功能

删除空行的空格 s :表示替换substitute, ^[ \t]:表示一空格或者tab开头的行, *:表示0到多个, $:表示行结束, g:表示全局global即替换整个文档中匹配的项

1
sed -i 's/^[ \t]*$//g" filename

删除空行 ^[ \t]:表示一空格或者tab开头的行, ×:表示0到多个, $:表示行结束, d:表示删除

1
sed -i "/^[ \t]*$/d" filename

将连续的多个空行删减为单个空行

1
sed -i '/^$/{N;/^.$/D} filename

###

详解

详解一

参考资源一: sed, a stream editor

详解二

参考资源二: Advanced Bash-Scripting Guide: Appendix C. A Sed and Awk Micro-Primer

Basic sed operators

Operator Name Effect
[address-range]/p print Print [specified address range]
[address-range]/d delete Delete [specified address range]
s/pattern1/pattern2/ substitute Substitute pattern2 for first instance of pattern1 in a line
[address-range]/s/pattern1/pattern2/ substitute Substitute pattern2 for first instance of pattern1 in a line, over address-range
[address-range]/y/pattern1/pattern2/ transform replace any character in pattern1 with the corresponding character in pattern2, over address-range (equivalent of tr)
[address] i pattern Filename insert Insert pattern at address indicated in file Filename. Usually used with -i in-place option.
g global Operate on every pattern match within each matched line of input

参考资源

参考资源一: sed, a stream editor

参考资源二: Advanced Bash-Scripting Guide: Appendix C. A Sed and Awk Micro-Primer