-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
2
  • 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
    Commented Sep 29, 2018 at 12:20
  • This is strongly related to unix.stackexchange.com/q/472204/4667 -- is this the same homework? Commented Sep 29, 2018 at 15:16

2 Answers 2

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.

1
  • Very elegant solution Commented Sep 29, 2018 at 15:39
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.

2
  • 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
    Commented Sep 29, 2018 at 16:46
  • The extended regex yes. The Perl regex no. Commented Sep 29, 2018 at 18:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .