Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert string or newline before a pattern "Using SED" ( Without replacing the pattern) In MAC OS

I have a file with the following content:

aaaabbaaabbaa

and i need an output like:

aaaa
bbaaa
bbaa

I need a new line to be added before first occurrence of 'b'. I need only SED command to use in bash

I am using the following command. I know its now the perfect one..

Can anyone tell me a better command than this. Pl note only SED command i need to use in bash

sed -i.bak  -e 's/bb/qbb/g' input.txt  
sed -i.bak  -e 's/qbb/\'$'\nbb/g' input.txt
like image 897
sam Avatar asked Oct 25 '13 12:10

sam


2 Answers

With sed:

$ echo "aaaabbaaabbaa" | sed -r 's/([b]+)/\n\1/g'
aaaa
bbaaa
bbaa

sed -r allows to catch blocks with () and print them back with \1. The block it catches it [b]+, meaning "one or more b's", and prints it back preceded by a new line.

As I see you are using sed -i, it is also good to do:

sed -i.bak -r 's/([b]+)/\n\1/g' input.txt

Also, easier (thanks Glenn Jackman!)

$ echo "aaaabbaaabbaa" | sed 's/b\+/\n&/g'
aaaa
bbaaa
bbaa

It replaces all sequences of "b" and replaces that with a newline followed by that same sequence of "b" (& represents whatever was matched on the left side of s///).

like image 149
fedorqui 'SO stop harming' Avatar answered Nov 19 '22 08:11

fedorqui 'SO stop harming'


grep -oP with lookahead regex will be easier:

echo 'aaaabbaaabbaa' | grep -oP '.+?[^b](?=(b|$))'

aaaa
bbaaa
bbaa
like image 37
anubhava Avatar answered Nov 19 '22 10:11

anubhava