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
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///
).
grep -oP
with lookahead regex will be easier:
echo 'aaaabbaaabbaa' | grep -oP '.+?[^b](?=(b|$))'
aaaa
bbaaa
bbaa
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With