Reputation: 1623
I am trying to replace the first occurrence of a space in each line with a newline.
For instance
123 there is a monkey
567 there is also a tiger
would become
123
there is a monkey
567
there is also a tiger
I have tried doing this with the command:
sed -e 's/^\s\+/\n/g' output.txt > new.txt
with no luck. I am also open to any other programs in linux that would allow me to do this such as awk, perl, or bash.
Upvotes: 3
Views: 1776
Reputation: 1716
Actually
sed -e 's/\s/\n/' output.txt > new.txt
should suffice. If you drop the global flag it will match the first char and sed works by line.
Upvotes: 0
Reputation: 95242
Lots of answers that work in GNU sed but not BSD sed (such as you'll find on a Mac). BSD sed, for example, won't turn \n
into a literal newline. Assuming you're in bash or modern ksh, you can use ANSI strings $'...'
to get around that problem. All of the answers below work in either version.
First, if you know for sure it's just one space, you can do this:
sed $'s/ /\\\n/'
If you want to handle the case where there may be more than one space in a row, you can do this:
sed $'s/ */\\\n/' # that's space, space, asterisk
Or you can use extended regular expressions:
sed -E $'s/ +/\\\n/'
If you want to handle arbitrary whitespace (e.g. tabs as well as spaces), then you can replace the literal space characters above with [[:space:]]
.
Alternately, you can use Perl, which has no version incompatibilities:
perl -pe 's/\s+/\n/'
Upvotes: 0
Reputation: 44023
Don't anchor the regex at the beginning of the line and ditch the g
flag:
sed -e 's/\s\+/\n/' output.txt > new.txt
EDIT: BSD sed part removed because of pain.
Upvotes: 2
Reputation: 41436
You could use this:
awk '{sub(FS,RS)}1' file
123
there is a monkey
567
there is also a tiger
It changes the first field separator with record selector.
Upvotes: 0
Reputation: 784878
You can use:
sed $'s/ \{1,\}/\\\n/' file
123
there is a monkey
567
there is also a tiger
This works both on BSD as well on gnu sed.
Upvotes: 3