Question

I am trying to replace a block in a file using sed, but with no success.

E.g. I want to replace this:

for(int i = 0; i < MAX_LOOPS; ++i) {
    printf("Hello World!");
}

With this:

int i = 0;
while(i < MAX_LOOPS) {
    printf("Hello World!");
    ++i;
}

No correct solution

OTHER TIPS

The following will do the trick but in a very basic way, i.e. it's not robust nor does it worry with formatting.

s/for(int i = 0; i < MAX_LOOPS; ++i)/int i = 0;\nwhile(i < MAX_LOOPS)/g /printf("Hello World!");/{ a++i; }

This is just a quick hack but it ought to be enough to get you going. Sed may not be the best tool for this job but it doesn't hurt to know how to do it in Sed.

This might work for you:

sed -e '/^for.* {/,/^}/{/for/{i\int i = 0;'\
>   -e ';c\while(i < MAX_LOOPS) {'\
>   -e '}};/^}/i\++i'  file
int i = 0;
while(i < MAX_LOOPS) {
    printf("Hello World!");
++i
}
sed -r '
    /for\s*\(.*;.*;.*\)/!b
    s#.*\((.*);(.*);(.*)\).*#\1\nwhile (\2) {\a\3#
    h
    s/.*\a//
    x
    s/\a.*//
    :X
    N
    /}/!{bX}
    G
    s#(.*)\n(.*)\n(.*)#\1\n   \3\n\2#
' file

int i = 0
while ( i < MAX_LOOPS) {
    printf("Hello World!");
    ++i
}
sed -e '
   /for(int i = 0; i < MAX_LOOPS; ++i) {/,/}/ {
      /}/ a \
int i = 0;\
while(i < MAX_LOOPS) {\
    printf("Hello World!");\
    ++i;\
}
      d
      }
   '  YourFile
  • delete all lines between for(int i = 0; i < MAX_LOOPS; ++i) { and }
  • when reaching } append the new content (before deleting the input line.

It use the different behaviour between input and ouptut. Append send info to output without putting this info in current working buffer (feed by input and moification) so delete cannot touch this but input (current line } here)is well touched

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top