Mico
Mico

Reputation: 413

How can I replace multiple newlines(\n) between characters using sed?

I have this sample file

{
    {
        doSomething();
    }


}

What I am trying to achieve is:

{
    {
        doSomething();
    }
}

I tried doing this

sed -r -i -e 's/}\n+}/}\n}/g' file.txt

but to no avail.

I want to remove the newlines between the closing parenthesis.

Note: I already read this How can I replace a newline (\n) using sed? and I am also aware of the N command but I can't create a working sed expression to achieve what I am trying to achieve.

Upvotes: 2

Views: 2722

Answers (3)

anishsane
anishsane

Reputation: 20980

Using awk:

awk -v RS='}' -v 'ORS=}' '!/{/{gsub(/\n+/,"\n")};1' file-name | head -n -1

Upvotes: 1

John1024
John1024

Reputation: 113834

Using sed:

$ sed 'H;1h;$!d;x; s/}\n\n*}/}\n}/g' file
{
    {
        doSomething();
    }
}

If you want to change the file in place, use the -i switch:

sed -i 'H;1h;$!d;x; s/}\n\n*}/}\n}/g' file  # GNU sed

sed -i '' -e 'H;1h;$!d;x; s/}\n\n*}/}\n}/g' file  # BSD sed

How it works

  • H;1h;$!d;x;

    This is a sed idiom which reads the whole file in to the pattern space. (If your file is huge, we would want to look at other solutions.)

  • s/}\n\n*}/}\n}/g

    This is just your substitute command with one change: \n+ is changed to \n\n*. This is because + is not an active character under basic regular expressions. If we use extended regex, then braces, { and }, become active characters which has the potential to lead to other issues for this input.

    Note that this removes the extra newlines only if the second closing brace, }, occurs at the beginning of a line.

Upvotes: 1

Thomas Baruchel
Thomas Baruchel

Reputation: 7517

It is not obvious what you exactly intend to do. However, if you want to work with multiline regexp you should be aware that in its classical form, sed isn't intended to work on more than one line at a time (maybe some multiline versions of sed have occured however). You can use other tools like perl. What I usually do when I need it is the following workflow:

tr '\n' 'µ' < myfile.txt | sed -e 's/µ}µ/}/' | tr 'µ' '\n'

(because the µ character is available on my keyboard and is most unlikely to appear in the file I am working with). The initial tr commands make one huge line from my file and the second tr command put the newline again at their initial locations.

Upvotes: 0

Related Questions