Your first example was close, but you're telling
sed that you want to take 2 characters at a time with the
\(.\)\(.\) bit, to do it using a capture group you could adjust it like so:
$ echo ahebhaaa | sed 's/\(.\)/\1\n/g'
As to why the
sed example with the
& works. The
& in a search and replace is what ever characters the regular expression matched. So everything that was not a
$ echo "123 abc" | sed 's/[0-9]*/&&/'
& prints the characters that were matched by the pattern (
123. The second
& prints them a second time.
$ echo "123 abc" | sed 's/ab/&&&/'
The pattern we're looking for is
ab. As we walk the string
123 abc sed is printing the non-matched characters,
123. Then the string
ab is encountered which at that point matches what we're searching and replacing on. So
sed then replaces it with 3 copies of what matched (
sed prints the
[^\n] creates a set of not a end of line character. So think of
sed as it's walking along your string of text,
ahebhaaa, it's testing each of these characters and saying "Is this not a
\n"? If it's not a end of line character, then
sed does a search and replace on this character and the
& prints what was matched, i.e. the character, along with a new line character. It then repeats this as it walks along the