3

I want to manipulate a textfile, so that blocks of indented lines will be enclosed with {{{ and }}}.

This is where I'm stuck:

  1 /^\ [^\ ]/,/^[^\ ]/{        # match range: all indented plus line after that
  2    b fixIndented            # branch
  3 }
  4 
  5 /^[^\ ]/{p;b}               # print all non-indented outside range and exit.
  6                             
  7 :fixIndented
  8 /^[^\ ]/{                   # match last line of range
  9    x;                       # swap Holdbuffer und patternSpace, edit patternSpace
 10    i\
 11       {{{
 12    a\
 13       }}}
 14    p;
 15    x;p;
 16 }
 17 H;                          # write each line in range into holdBuffer

I think line 15 should read in the hold buffer (containing what I swapped there in line 9) and then print it, after the manipulated pattern space (lines 10-13) has been printed (14). But that doesn't happen. Instead, it appears to merge the line from the hold buffer into the pattern space. Like so:

bla
blubb
 foo1
 bla2
 foo3
sadgfasdf
bar
foo

becomes:

bla
blubb
      {{{

 foo1
 bla2
 foo3
sadgfasdf
      }}}   
bar
foo

I'd be very grateful if somebody took the time to point me into the right direction here. Thanks,

2
  • +1 for good question with interesting problem. ..... But unless your "married" to sed, awk would be a much easier solution to this problem. Good luck
    – shellter
    Sep 10, 2013 at 16:44
  • interesting ! Good exercise. Lets try !
    – Utopik
    Sep 10, 2013 at 17:06

1 Answer 1

2

It is possible with sed also but with awk it is much simple:

cat file
bla
blubb
 foo1
 bla2
 foo3
sadgfasdf
bar
foo

awk '!s && /^ /{s=1; $0 = " {{{" ORS $0} s && /^[^ ]/{s=0; $0 = " }}}" ORS $0}1' file
bla
blubb
 {{{
 foo1
 bla2
 foo3
 }}}
sadgfasdf
bar
foo
2
  • 2
    @michaelP: I told you it would be easier ; -) Good luck to all.
    – shellter
    Sep 10, 2013 at 17:46
  • 1
    That solves the problem, thank you very much! I'll have to check how it blends in with the bigger context tomorrow at work (that is, see if the indented braces will be a problem), but it is an impressive one-liner, doing what I wanted! @shellter: No, I'm not married to sed, and seeing how easy this has been solved with awk, I sure would think about filing a divorce now :)
    – Michael P
    Sep 10, 2013 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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