-1

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

/*
    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 解决方案和白痴解释。问候!

4

1 回答 1

0

我做的。很确定必须有一个更简单的解决方案。这会找到匹配的行号,将其存储,然后从那里向后循环到第一个 /* 。之后,相同的过程,其他方向直到 */ 。该死的丑陋,但可能对某人有用。非常欢迎改进建议!

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
于 2014-11-06T21:36:36.597 回答