How to add line break using sed?

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/" to no avail. The default is OK, but the addition of the new line does not. I need to know what to put there where it is \n .

Examples of results I hope:

No Match:

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

Expected output:

bravo bar

Match:

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

Expected output:

foo
bar
    
asked by anonymous 31.07.2014 / 15:53

3 answers

1

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

echo 'foo bar' | sed 's/.*oo/&\'$'\n/g'
    
31.07.2014 / 16:02
1

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

This here generates the expected output:

echo 'foo bar' | sed 's/\(.*oo\) \(.*\)/\n/g'
    
31.07.2014 / 16:02
1

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

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

output

foo
bar

@HenriqueBarcelos presented some richer examples with re-use of substrings which obviously works great on GnuSed.

To highlight the potentiality of this issue, along with a slightly more complex example that changes site line breaks:

  • involves multiline patterns
  • involves captures
  • involves mutilating substitutions.

Case study: Correct broken words by translineation

Given a text with broken words:

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

change the word continuations to the previous line!

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