0

It's common to use Sed (or Perl or Ruby) to replace things in a file:

sed -i.bak 's/\s+\\{/ {/g' some.code

In this example I want to remove line breaks before curly braces in code, since they are not part of my programming 'dialect' (for any language I use) and make reading the code less natural and smooth. But the basic problem is how to match a pattern that spans lines, rather than a pattern that is within any given line of the file.

Existing SO questions that appear to be similar did not specifically address how to span across lines in general, but instead gave solutions to the specific problem the user was trying to solve, sometimes through workarounds instead.

I poked around in the Sed man pages and couldn't find any switches to do what I'm describing. Perhaps I'm just not looking with the right keywords, though.

BMW
  • 42,880
  • 12
  • 99
  • 116
iconoclast
  • 21,213
  • 15
  • 102
  • 138
  • unfortunately sed AFAIK doesn't work well with line breaks: http://stackoverflow.com/questions/1251999/sed-how-can-i-replace-a-newline-n some other tool might work better :) – rogerdpack Jan 06 '14 at 22:57
  • 1
    It's easy with Perl and the [`m` regex modifier](http://perldoc.perl.org/perlre.html#Modifiers). – nwellnhof Jan 06 '14 at 22:59
  • @nwellnhof: if you give an answer with Perl I'll accept it... I knew I'd seen that switch before, I just didn't realize it was in Perl but missing from Sed. – iconoclast Jan 07 '14 at 04:12
  • 1
    Sed can be used to work on several lines directly, see this URL first: http://www.thegeekstuff.com/2009/12/unix-sed-tutorial-6-examples-for-sed-branching-operation/, if you can provide the sample input file, we can provide the solution directly. – BMW Jan 07 '14 at 06:37

2 Answers2

1

Using sed:

sed -r ':a;N;$!ba;s/\s+\{/ {/g' some.code
BMW
  • 42,880
  • 12
  • 99
  • 116
0
sed -r -unbuffered '$ !{N;s/\n[[:blank:]]*{/ {/;P;D;};$ p' some.code

allow to work on huge file (stream version). On small and medium (several thousand of line at least) the code of @BMW is more efficient i imagine (1 request of substitution, in this code, substitution at each loaded line)

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43