2

For example if I have a file as follow:

1  2  3  4  5  6
7  8  9  10  11  12

And I want to reorganize this file as:

1
2
3
4
5
6
7
8
9
10
11
12

Can I use the awk command for that or not?

pelumi
  • 1,530
  • 12
  • 21
Sky
  • 33
  • 5
  • Seen this: [I'm trying to create a dictionary of words from a collection of files. Is there a simple way to print all the words in a file, one per line?](http://stackoverflow.com/questions/1123572/extract-words-from-a-file) ? – pelumi Oct 14 '15 at 09:56

3 Answers3

0

There are multiple ways to achieve this.

With grep:

grep -oE "[0-9]+" file
  • The -o flag prints only the matching patterns (the digits in this case), delimited by newline
  • -E activates extended regular expressions.

With awk:

awk 'OFS="\n"{$1=$1}1' file
  • OFS defines the output field separator.
  • $1=$1 because we changed the OFS, we need to rebuild the line by setting the first field to itself, this will force the rebuild.
  • 1 at least we need a true condition that the line is printed.
chaos
  • 8,162
  • 3
  • 33
  • 40
  • Could you please explain the command? For example what does -oE do in grep? what dose OFS mean? Sorry I am really beginner... – Sky Oct 14 '15 at 09:56
  • I prefer awk command and recently I find it super useful in my work... Thanks a lot and this awk can do my job and I will figure out the meaning or this sentence... – Sky Oct 14 '15 at 10:00
  • @Sky I added explantions to my answer – chaos Oct 14 '15 at 10:03
  • thanks! I will try to work more on awk. – Sky Oct 14 '15 at 11:12
0

With sed:

TMP$ sed -r 's/ +/\n/g' File
1
2
3
4
5
6
7
8
9
10
11
12

Replace all continuous spaces with newline.

Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
  • Thanks! But this commend will create one empty line in between the data from different column. awk 'OFS="\n"{$1=$1}1' gives one column without any empty line. – Sky Oct 14 '15 at 10:04
  • That's possibly because each line is terminating with one or more space... – Arjun Mathew Dan Oct 14 '15 at 10:08
0

The naive AWK approach:

#!/usr/bin/awk -f

{ for (i = 1; i <= NF; i++) print $i; }

Chaos's approach is probably more efficient.

Ruud Helderman
  • 10,563
  • 1
  • 26
  • 45