-1

I have a text file, I want to print every word (more than one character) on new line. If a word consist of a single character, it must be handled as part of the following word and printed with it on a new line. If it is in the middle between two words it must follow the second word. example:

Unix & Linux Stack Exchange is a question and answer site for users of Linux,

output

Unix
& Linux
Stack
Exchange
is 
a question 
and 
answer 
site
for
users
of
Linux
  • What do you mean by "if it is in the middle between two words it must follow the second word"? What should happen to a one character word if there's no word following it? – choroba Sep 29 '18 at 12:20
  • This is strongly related to unix.stackexchange.com/q/472204/4667 -- is this the same homework? – glenn jackman Sep 29 '18 at 15:16
1

I'd reach for Perl-flavoured regex here:

$ echo "$s" | grep -Po '((^|\s)\K\S\s+)?\S{2,}'
Unix
& Linux
Stack
Exchange
is
a question
and
answer
site
for
users
of
Linux,

You can do the same with extended regex, but as it doesn't have pcre's lookarounds, you end up capturing the leading space:

$ echo "$s" | grep -Eo '((^|[[:blank:]])[^[:blank:]][[:blank:]]+)?[^[:blank:]]{2,}'
Unix
 & Linux
Stack
Exchange
is
 a question
and
answer
site
for
users
of
Linux,

I would have liked to use a word boundary marker prior to the 1-character word, but & is not a word character, so the word boundary is not useful.

  • I really appreciate the answer. Very helpful! I Googled so much but I was not aware that there was similar question out there. thanks for sharing! Can I use the same regex in an awk statement? – Zahi Sep 29 '18 at 16:46
  • The extended regex yes. The Perl regex no. – glenn jackman Sep 29 '18 at 18:49
2

How about

sed -r 's/([^ ]{2,}) /\1\n/g' file
Unix
& Linux
Stack
Exchange
is
a question
and
answer
site
for
users
of
Linux,

Check if a space is preceded by 2 or more non-space char pattern, and substitute by "back reference" pattern plus <LF> char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.