Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a line-feed/newline BEFORE a pattern using sed

Tags:

sed

awk

The title already states it:

I want to use some linux one liner (e.g. sed)

to transform

Anytext
{

into

Anytext{

Can this be done using sed or if not with sed then with an awk one liner ?

like image 688
Martin Avatar asked Aug 26 '12 11:08

Martin


2 Answers

Sure,

sed 'N;s/\n{/{/'

Or a more thorough version:

sed ':r;$!{N;br};s/\n{/{/g'

Here, :r sets a label that we can refer to in order to create a loop;

$!{...} executes the given set of commands for every line except the last one;

N;br are two commands the get executed in the loop: N appends a new line to the pattern space, and br branches back to the label r, completing the loop.

Then you have all of your file in pattern space when you run the final command:

s/\n{/{/g

You can see the difference between the two approaches if you try it on something like

Anytext
{
{
{
like image 167
Lev Levitsky Avatar answered Oct 19 '22 07:10

Lev Levitsky


One way using sed:

sed -ne '$! N; /^.*\n{/ { s/\n//; p; b }; $ { p; q }; P; D' infile

A test. Assuming infile with content:

one
Anytext
{
two
three
{
four
five
{

Output will be:

one
Anytext{
two
three{
four
five{
like image 2
Birei Avatar answered Oct 19 '22 07:10

Birei