5

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?

7

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.

3
  • Many thanks. That was concise and correct. Is there a similar command to simply delete the comment slashes if they occur on a line with LogMsg()?
    – pdm
    Feb 20 '14 at 16:36
  • s? is the opposite of s^ I take it?
    – pdm
    Feb 20 '14 at 16:39
  • @musasabi No. The question mark is just a separator. The string beginning with s means: substitute the // with nothing. The ? identifies where the string to be replaced,and its replacement, begin and end. And yes, a better reverse is (forget the one above: sed 'LogMsg/ s?^//?^?' filename > new_filename. The hat ^ indicates the beginning of the line, the dollar sign $ indicates the line end. Feb 20 '14 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.