Linux/Bash: Comment every line matching a pattern

Posted on

Problem :

sed is foreign to me, to say the least. I’d like to traverse a C project tree and comment out every line calling the function LogMsg(). Something that’d achieve the following:

foreach: line within *.c
  if: line contains "LogMsg"
    prepend "//"

Or so. Also, then, I’d like to see if I could achieve the reverse, though I imagine that might be more difficult.

I feel like sed is the right tool for this job, but I’m no expert in batch text file edits. Any help?

Solution :

The command to use is:

 sed '/LogMsg/ s?^?//?' filename  new_filename

It locates the lines, in the file filename, containing LogMsg, and substitutes at the beginning of the line (^), the double slash. The question mark is used as a delimiter instead of the more usual slash, to prevent confusion with the text to be substituted. The output is redirected to the new version of the file, instead of the standard output.

Leave a Reply

Your email address will not be published. Required fields are marked *