ClaudioM
ClaudioM

Reputation: 1446

Replace curly braces separated by a newline with sed

I need to replace this

    },   <-here there is a \n
    {

with

}{

Doesn't matter about \n

I've tried this :

sed "s/},\n{/}{/g" 

but doesn't work.

I've tried other strange solutions but don't work as well because in the file there are a lot of others rows that start with {.

Could you please suggest some solution?

Upvotes: 3

Views: 1421

Answers (4)

potong
potong

Reputation: 58351

This might work for you (GNU sed):

sed 'N;s/},\n\s*{/}{/;P;D' file

Create a moving window of two lines and replace the newline separated pattern when appropriate.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203129

sed is for simple subsitutions on individual lines, that is all. What you're trying to do crosses 2 lines and so is not a job for sed. Just use awk, e.g.:

awk -v RS= '{gsub(/},\n{/,"}{")} 1' file

The above will work portably with all awks in all shells on all UNIX systems (the sed solutions you have so far will only work in some seds and so are not portable).

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191729

You can use the -z option for sed which separates lines by null characters instead of newlines. You may want to use it with -u if it's a particularly large file.

sed -z "s/},\n{/}{/g" 

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

sed solution:

Sample test.txt file:

afa
asdasd
},
{
sdfasd
},
{

sed '/},$/{ N; s/,\n{/{/; }' test.txt

The output:

afa
asdasd
}{
sdfasd
}{

Upvotes: 3

Related Questions