Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed or awk multiline replace

Tags:

multiline

sed

awk

I am trying to append formatting to all /* TODO : ... */ tags, but I am having trouble in the multi-line area. I can do single line sed's; but for multiline sed and awk, I don't know.

How do I do this? I'm open to either. Here's what I have so far.

sed 's/\/\/\*[ \t]*TODO[ \t]*:.*/*\//<span style="color:#aaaaaa;font-weight:bold;">&</span>/g'

replace :

int void main ( int h, char * argv[] )
  int a, b; /* TODO :
               - include libraries
               ...
            */
  foobar();
  /* TODO : fix missing {'s */

with :

int void main ( int h, char * argv[] )
  int a, b; <span style="color:#aaaaaa; font-weight:bold;">/* TODO :
               - include libraries
               ...
            */</span>
  foobar();
  <span style="color:#aaaaaa; font-weight:bold;">/* TODO : fix missing {'s */ </span>
like image 505
rlb.usa Avatar asked Mar 04 '10 03:03

rlb.usa


People also ask

Does sed support multiline replacement?

By default, when sed reads a line in the pattern space, it discards the terminating newline (\n) character. Nevertheless, we can handle multi-line strings by doing nested reads for every newline.

Is awk faster than sed?

I find awk much faster than sed . You can speed up grep if you don't need real regular expressions but only simple fixed strings (option -F). If you want to use grep, sed, awk together in pipes, then I would place the grep command first if possible.

Can awk replace?

awk has two functions; sub and gsub that we can use to perform substitutions. sub and gsub are mostly identical for the most part, but sub will only replace the first occurrence of a string. On the other hand, gsub will replace all occurrences. Let's take a closer look at how we can make substitutions using awk.


1 Answers

gawk 'BEGIN{
  RS="*/"
  replace="<span style=\"color:#aaaaaa; font-weight:bold;\">"
}
/\/\* +TODO/{
    gsub(/\/\* +TODO/,replace" /* TODO")
    RT=RT "</span>"
}
{ print $0RT}
' file

output

$ ./shell.sh
int void main ( int h, char * argv[] )
  int a, b; <span style="color:#aaaaaa; font-weight:bold;"> /* TODO :
               - include libraries
               ...
            */</span>

  foobar();
  <span style="color:#aaaaaa; font-weight:bold;"> /* TODO : fix missing {'s */</span>
like image 118
ghostdog74 Avatar answered Oct 18 '22 21:10

ghostdog74