Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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)

share|improve this question

4 Answers 4

up vote 10 down vote accepted

Try the below command

awk -v RS=" " '{print}' file

OR

awk -v RS='[\n ]' '{print}' file

Example:

$ awk -v RS=" " '{print}' example
abc
cdef
ghi
jk
lmnopq
rst
uv
wxyz

Explanation:

RS (Record seperator) is an built-in awk variable. In the first command, the value given to the Record separator variable is space. so awk breaks the line from printing whenever it finds a space.

In the second command, the value given to the RS variable is space or a new line character.This command eliminates the extra blank line appeared while running the first command.

share|improve this 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}
    
share|improve this answer
    
Your first 3 choice are correct! But last option gives error bash: ${${"$(cat pkghad)"}// /\\n}: bad substitution –  Pandya May 5 at 14:49
    
@Pandya sorry, that was the wrong one, I was playing around with it and pasted one of the bad versions. Try again with the edited answer. –  terdon May 5 at 14:50

You can use xargs,

cat example | xargs -n 1

or, better

xargs -n 1 < example
share|improve this answer
4  
xargs -n 1 < example saves you 1 kitten –  Rinzwind May 5 at 14:48

Using a perl oneliner:

perl -p -i -e 's/\s/\n/g' example

It will replace spaces and tabs with "ENTER" (aka \n)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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