注释掉行,仅当后续行包含匹配的字符串时

时间:2016-07-05 18:09:09

标签: awk sed

与此问题相反Comment out line, only if previous line contains matching string ...我想使用sedawk注释掉包含if的行,但仅限于以下行包含specific

在这个例子中:

...

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

...

我希望以if开头的行注释掉,因为以下行包含specific

2 个答案:

答案 0 :(得分:2)

在这个问题中如何做你可能会要求的事情:

$ cat preCmt.awk
{
    print ((pre ~ /^[[:space:]]*if/) && /specific/ ? "#" : "") pre
    pre = $0
}
END { print pre }

$ awk -f preCmt.awk file

...

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

...

以及您在上一个问题中要求做的事情:

$ cat postCmt.awk
{
    print (/^[[:space:]]*else/ && (pre ~ /specific/) ? "#" : "") $0
    pre = $0
}

$ awk -f postCmt.awk file
...

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

...

以上内容将在所有操作系统的所有awks中高效且稳健地运行,并且如果/当您的需求发生变化时,将很容易增强。

答案 1 :(得分:1)

使用sed:

sed '/^if/{N;/specific/{s/^/#/}}' file

添加-i选项以编辑文件

sed -i '/^if/{N;/specific/{s/^/#/}}' file