Ubuntu – How to replace spaces with newlines/enter in a text-file

command linetext processing

I have simple text file named "example".

Reading with terminal command: cat example

Output:

abc cdef ghi jk lmnopq rst uv wxyz

I want to convert (transform) into following form: (expected output from cat example)

abc
cdef
ghi
jk
lmnopq
rst
uv
wxyz

How can I do this via the command-line?

(This is only an example file, I want to convert word's position in vertical-column)

Best Answer

A few choices:

  1. The classic, use tr:

    tr ' ' '\n' < example
    
  2. Use cut

    cut -d ' ' --output-delimiter=$'\n' -f 1- example
    
  3. Use sed

    sed 's/ /\n/g' example
    
  4. Use perl

    perl -pe 's/ /\n/g' example
    
  5. Use the shell

    foo=$(cat example); echo -e ${foo// /\\n}