How to add line break using sed?

Asked

Viewed 5,312 times

1

How to add a line break in a pipe received output, using sed, only for cases that fit the established pattern?

I used sed "s/.*oo.*/&\n/" unsuccessfully. The pattern is OK, but the addition of the new line is not. I need to know what to put there where it is \n.

Examples of results I hope:

Sem Match:

echo 'bravo bar' | sed "s/.*oo.*/&\n/"

expected output:

bravo bar

Match:

echo 'foo bar' | sed "s/.*oo.*/&\n/"

expected output:

foo
bar

3 answers

1

& represents ALL the string that matches the pattern, so you’re just adding a line break to the end of the line.

This generates the expected output here:

echo 'foo bar' | sed 's/\(.*oo\) \(.*\)/\1\n\2/g'
  • The output of your command is: foonbar

  • It’s not no... Tested before posting.

  • In which OS? In OS X the result is foonbar

  • That’s why on Mac the line break is \r, nay \n. Just make the switch to work.

  • if I switch to r foorbar

  • I’ve never used OS X, it’s probably some question with Escaping. Try with \\r and see the result.

  • I’ll use the other answer, but thanks anyway!

  • But it works with \\r? Now even I want to know the answer

  • 1

    output: foo\rbar

  • 2

    the standard version of sed in OS X is not the gnu sed, so the differences in output. Output works as expected in gnu sed. Out of curiosity, the sed default on OS X is the same as found on Freebsd.

  • @Brunocoimbra, this is always a headache! Fortunately the homebrews and the like have the gnused version of easy installation. In some cases the Macs have gnused installed with the name gsed or gnused. gnused (and gnu awk) functionality is significantly richer.

Show 6 more comments

1


Use sed 's/.*oo.*/&\'$'\n/g' but to catch foo you need to improve the standard:

echo 'foo bar' | sed 's/.*oo/&\'$'\n/g'
  • 'Cause you need that part: '$'?

  • worked. Thank you

  • The $ indicates the inclusion of a new line which is complemented with \n

1

Using Gnu-sed (present in linux and easy to install everywhere, and to times with the name gsed) the example proposed by OP works with slight modification:

sed echo 'foo bar' | sed 's/.*oo/&\n/'

output

foo
bar

@Henriquebarcelos presented some richer examples with reuse of substrings which obviously works very well on Gnused.

To highlight the potentiality of this issue, I put together a slightly more complex example that changes site line breaks:

  • involves multiline patterns
  • involves catches
  • involves small substitutions.

Case study: correct broken words by translating

Given a text with broken words:

$ cat texto
Exemplo
aqui vai um tex-
to que tem trans-
lineações a dar
com um pau!

move word continuation to the previous line!

$ sed -zre 's/-\n([^ ]+) /\1\n/g'  texto
Exemplo
aqui vai um texto
que tem translineações
a dar
com um pau!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.