Bash:找到字符串并删除其周围的c注释符号(最好是就地编辑)



我已经为此烦恼了很长一段时间:我需要在文本文件中匹配一个字符串,并删除它周围的C注释。编辑应该在原地或新文件中(然后我会移动mv命令来推送它)。

/*
    might be text here;
    STRING_TO_MATCH
    some text;
    more text
    maybe brackets ( might be text and numbers 123);
*/

所以字符串很容易找到,但我如何删除注释?行数并不总是相等的。我无法理解这一点,因为删除必须是非贪婪的(同一文件中有类似的数据不应该被更改),并且整个"模式"是多行的。期望输出:

    might be text here;
    STRING_TO_MATCH
    some text;
    more text
    maybe brackets ( might be text and numbers 123);

我想工作流程应该是这样的:

找到string_to_match,先找到前面的/*并删除它,然后再删除后面的*/。

如果该解决方案也能自动适用于,那就太好了

/*  STRING_TO_MATCH
    some text;
    more text
    maybe brackets ( might be text and numbers 123);
*/

非常感谢提前从一个Bash业余爱好者!我在SED方面并不成功。AWK解决方案和防白痴解释也很受欢迎。问候!

我做到了。肯定会有更简单的解决方案。这会找到匹配的行号,存储它,然后从那里向后循环到第一个/*。之后,按照相同的程序,其他方向直到*/。他妈的丑,但可能对某人有用。非常欢迎提出改进建议!

STRING_TO_MATCH="STRING_TO_MATCH"
file="/home/simon/testfile"
match_line=`cat $file | grep -n "$STRING_TO_MATCH" | awk '{print $1}' | sed 's/://g' `
for (( i=0; i<=20; i++ )) #20 is just a treshhold
do
    search_line=`expr $match_line - $i`
    if sed -e "$search_line!d" $file | grep '/*'
    then
        sed -ie "$search_line s//*//" $file
        break 
    fi
done
for (( i=0; i<=20; i++ )) #20 is just a treshhold
do
    search_line=`expr $match_line + $i`
    if sed -e "$search_line!d" $file | grep '*/'
    then
        sed -ie "$search_line s/*///" $file
        break 
    fi
done

最新更新