如何用sed在Bash脚本的注释块后添加空行?
在Bash脚本的注释块与代码间插入空行(sed实现)
需求
要处理一批Bash脚本,给连续注释块(以#开头的行)和紧跟其后的非注释代码行之间插入一个空行,比如:
原代码示例1:
# first comment goes here # second comment goes here if [[ -n "$some_variable" ]]; then do_something fi
原代码示例2:
# first comment goes here # second comment goes here # third comment goes here if [[ -n "$some_variable" ]]; then do_something fi
处理后要变成:
示例1处理后:
# first comment goes here # second comment goes here if [[ -n "$some_variable" ]]; then do_something fi
示例2处理后:
# first comment goes here # second comment goes here # third comment goes here if [[ -n "$some_variable" ]]; then do_something fi
解决方案
直接用sed命令即可完成批量处理:
测试命令(不修改原文件,输出到终端预览效果)
sed '/^#.*$/{n;/^[^#]/s/^\n/&\n/}' your_script.sh
直接修改文件(建议先备份原文件再执行)
sed -i '/^#.*$/{n;/^[^#]/s/^\n/&\n/}' your_script.sh
如果是macOS系统,sed的-i参数需要添加空后缀:
sed -i '' '/^#.*$/{n;/^[^#]/s/^\n/&\n/}' your_script.sh
命令逻辑解释
/^#.*$/:精准匹配所有以#开头的注释行{n; ...}:对匹配到的注释行执行后续操作,n表示把下一行内容读入当前模式空间/^[^#]/:判断读入的下一行是否不是以#开头(非注释的代码行会被匹配,空行不会触发,因为空行是^$)s/^\n/&\n/:如果满足条件,就在该非注释行的前面插入一个空行——&代表匹配到的行首换行,替换后相当于多添加一个换行符
这个命令只会处理「注释行直接紧跟非注释代码行」的场景,不会影响注释行后面本来就有空行的情况,避免插入多余空行。
内容的提问来源于stack exchange,提问作者CMPXCHG8B
相关产品推荐
相关产品推荐

