30

Is it possible to do something like this:

$ cat foo.txt
1 2 3 4
foo bar baz
hello world
$ awk '{ for(i in $){ print $[i]; } }' foo.txt
1
2
3
4
foo
bar
baz
hello
world

I know you could do this:

$ awk '{ split($0,array," "); for(i in array){ print array[i]; } }' foo.txt
2
3
4
1
bar
baz
foo
world
hello

But then the result is not in order.

Tyilo
  • 28,998
  • 40
  • 113
  • 198

4 Answers4

64

Found out myself:

$ awk '{ for(i = 1; i <= NF; i++) { print $i; } }' foo.txt
Tyilo
  • 28,998
  • 40
  • 113
  • 198
1

No need for awk, sed or perl. You can easily do this directly in the shell:

for i in $(cat foo.txt); do echo "$i"; done
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

I'd use sed:

sed 's/\ /\n/g' foo.txt
DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
dala
  • 1,975
  • 3
  • 14
  • 15
  • Doesn't work because I need to manipulate the seperated fields in awk. Or then I have to both involve sed and awk – Tyilo Aug 09 '11 at 14:44
-1

If you're open to using Perl, either of these should do the trick:

perl -lane 'print $_ for @F' foo.txt
perl -lane 'print join "\n",@F' foo.txt

These command-line options are used:

  • -n loop around each line of the input file, do not automatically print the line
  • -l removes newlines before processing, and adds them back in afterwards
  • -a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace.
  • -e execute the perl code
Chris Koknat
  • 3,305
  • 2
  • 29
  • 30