I have a string like: testfsdfsdftestfsdkflsdtestsdfsdfsdf
I am wondering how to separate the string so that testfsdfsdf
appears on the first line, testfsdkflsd
will appear on the second line, etc. like this:
testfsdfsdf
testfsdkflsd
testsdfsdfsdf
I tried using sed
to find test
and anything after it with sed 's/test.*/
but I am wondering how to reprint test.*
again. From what I know with sed
, you can use it to find a particular string and then replace it with something else. So essentially, I wanted to try something like sed 's/test.*/[reprint test.* here]\n/g'
, but if I do sed 's/test.*/test.*\n/g'
, it just outputs test.*
. Is there any way I can reprint the string found with sed
, or can this be done with another command?
I also tried sed 's/\(test.*\)test/\1\ntest/g'
, which works if there are only two instances of test[random characters]
, but not three or more. With the string testfsdfsdftestfsdkflsdtestsdfsdfsdf
, it only prints:
testfsdfsdftestfsdkflsd
testsdfsdfsdf
You are close. The sed command you want is
It prepends a newline character to each
test
.Now, although GNU sed and possibly others do it, the interpretation of
\n
as a newline is not specified by POSIX. To make the command portable, a literal, escaped newline is required,You will notice, however, that if
test
is the very first four characters of the line, as is the case with your example, that will create an empty line at the beginning of the output. If that is not to happen, we can use.
matches any character, so the existence of some character beforetest
is required, otherwise the regex does not match. I.e., iftest
is the first string in the line, then.
can't match anything and the substitution is not made.And for the portable alternative,
Some tests with GNU sed:
That's because
.*
is greedy, i.e., it will match all it can. For example,colors/matches everything from the first to the last
b
.