0

I want to split each line from input file by a non-alphanumeric regex \W and print all the split chunks in the output file like so:

Input file:

www.wifi.in.ua
YI-HondBrychka

Output file:

www
wifi
in
ua
YI
HondBrynchka
1

Try using the -o flag, to only print matching strings, e.g.

$ cat <<HEREDOC | grep -Po '\w+'
www.wifi.in.ua
YI-HondBrychka
HEREDOC

www
wifi
in
ua
YI
HondBrychka
  • Did you mean grep -Po '\w+' HEREDOC? This works, thank you. – dizcza Mar 10 at 19:33
  • No, I meant what I wrote there - it works for me if I copy-paste it. In practice, I imagine you would use a file instead of a heredoc string, and it would look like grep -Po '\w+' /path/to/file. – igal Mar 10 at 19:55
  • Substituting HEREDOC for path to file, cat <<HEREDOC | grep -Po '\w+' doesn't work for me while cat HEREDOC | grep -Po '\w+' (or better grep -Po '\w+' HEREDOC) works fine. – dizcza Mar 10 at 19:59
  • It sounds to me like you're confused about what a heredoc is - it's not supposed to represent a file path. You can read more about "here documents" in the Bash manual: gnu.org/software/bash/manual/bashref.html#Here-Documents – igal Mar 10 at 20:03
  • Oh, I see, I didn't know that. Thank you. – dizcza Mar 10 at 20:07
0

Replacing all matches of \W with newlines, using Perl (from which the \W expression originated):

$ perl -pe '$_ =~ s/\W/\n/g' <file
www
wifi
in
ua
YI
HondBrychka

Or, more in line with the actual wording of the question:

$ perl -pe '$_ = join("\n", split(/\W/)) . "\n"' <file
www
wifi
in
ua
YI
HondBrychka

Expressing the PCRE \W as the ERE [^[:alnum:]] and using GNU awk:

awk -v RS='[^[:alnum:]]' 1 file

The 1 is short for '{ print }' and this sets the input record separator to any \W character. The records are then printed on individual lines.

Or with GNU sed:

sed 's/[^[:alnum:]]/\n/g' file

With tr, it becomes

$ tr -c '[:alnum:]' '\n' <file
www
wifi
in
ua
YI
HondBrychka

where -c makes it replace each character that is not an [:alnum:] with a newline.

  • The last solution has an artifact of empty new lines. Compare tr -c '[:alpha:]' '\n' < HEREDOC with grep -Po '[a-zA-Z]+' HEREDOC if we add "Zhenek_Lebed98" to the input file HEREDOC. – dizcza Mar 10 at 19:57
  • @dizcza Add -s to the command line. It will make it squeeze multiple newlines into one. But on the other hand, you do have an empty word between 9 and 8. – Kusalananda Mar 10 at 20:03
  • Now it works as well. – dizcza Mar 10 at 20:04

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.