-1

I am bothered with this for a long time already: I need to match a string in a text file and remove the C-commentary around it. The edit should be inplace or into a new file (I will then move mv-command to push it).

/*
    might be text here;
    STRING_TO_MATCH
    some text;
    more text

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

So the string is easy to find, but how can I remove the commentary? The number of lines is not always equal. I couldn't figure that out because the removal must be non-greedy (there is similiar data in the same file that shouldn't be altered) and the overall "pattern" is multiline. Desired output:

    might be text here;
    STRING_TO_MATCH
    some text;
    more text

    maybe brackets ( might be text and numbers 123);

I guess the workflow should be like:

Find string_to_match, find preceding first /* and remove it and then remove following first */.

It would be great if the solution would automatically also work for

/*  STRING_TO_MATCH
    some text;
    more text

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

Great thanks in advance from a Bash-amateur! I was not successful with SED. AWK solutions and idiot-proof explanation also welcome. Greetings!

simonarne
  • 1
  • 1

1 Answers1

0

I did it. Pretty sure there must be an easier solution. This find the line number of the match, stores it and then loops backwards from there to the first /* . After that, same procedure, other direction until */ . Damn ugly, but might be useful to someone. Improvement suggestions very welcome!

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
simonarne
  • 1
  • 1