注释掉行,只要previous行包含字符串匹配 [英] Comment out line, only if previous line contains matching string

查看:108
本文介绍了注释掉行,只要previous行包含字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一种使用庆典脚本的解决方案 SED AWK 注释掉一条线,只有previous行包含匹配的字符串。

例如,包含文件:

  ...如果[$ V1 -gt 100];然后
一些特定的命令
其他
其他一些特定的命令
科幻...

我想注释掉包含行其他但前提是previous行包含具体

我已经尝试多种管道 SED 的grep 命令沿着命令无济于事。


解决方案

  SED -E'/特定/ {N; S / ^([:空白:] *)其他$ / \\ 1#否则/}'

输出

  ...如果[$ V1 -gt 100];然后
一些特定的命令
#其他
其他一些命令
科幻...

的回顾


  1. /特定/ 查找包含该模式的行的具体的

  2. N 下一行添加到模式空间。 N 自动打印出当前模式空间。

  3. 检查下一行是(one_or_more_spaces)其他,如果是,替换了行(one_or_more_spaces_found_ previously)的#else 。记住()是模式重用和 \\ 1 是previously匹配的模式重复使用。

  4. -E 启用扩展的正则表达式

  5. -i 是就地实际文件的修改

Looking for a solution for a bash script using sed or awk to comment out a line, only if the previous line contains a matching string.

For example, a file containing:

...

if [ $V1 -gt 100 ]; then
some specific commands
else
some other specific commands
fi

...

I'd like to comment out the line containing else but ONLY if the previous line contains specific.

I've attempted piping multiple sed commands along with grep commands to no avail.

解决方案

sed -E '/specific/{n;s/^([[:blank:]]*)else$/\1#else/}'

Output

...

if [ $V1 -gt 100 ]; then
some specific commands
#else
some other commands
fi

...

A retrospection

  1. /specific/ look for the line containing the pattern specific
  2. n add the next line to the pattern space. n auto prints the current pattern space.
  3. Check if the next line is (one_or_more_spaces)else,if yes, substitute the line with a (one_or_more_spaces_found_previously)#else. Remember () is for pattern reuse and \1 is the previously matched pattern reused.
  4. -E enable extended regex
  5. -i is for inplace edit of the actual file

这篇关于注释掉行,只要previous行包含字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆