-2

My data sample seems:

1 2 3 4 5
4 5 6 7 9 9 0
1 2 3 4
1 8 7 6 9

and I want to change in to :

1
2
3
4
5
4
5
6
7
9
9
0
1
2
3
4
1
8
7
6
9
2
  • yes u r right this is a sample data.
    – shu
    Aug 27, 2017 at 22:33
  • Dear Mr. Roaima, would you format it with ur comment
    – shu
    Aug 27, 2017 at 22:41

5 Answers 5

3

If input lines doesn't have spaces use this:

fold -1 data_sample.txt

fold - wrap each input line to fit in specified width.

In this case the width is the one column, specified by -1 option.


If input has spaces, but you want omit them, use this:

grep -o '\S' data_sample.txt

\S - matches any non-white-space character.

-o - print every matched parts on a separate line.

2

Using the rs (reshape) utility:

$ rs 0 1 < data
1
2
3
4
5
4
5
6
7
9
9
0
1
2
3
4
1
8
7
6
9

The output array shape is determined from the optional row and col arguments as follows:

If only one of them is a positive integer, rs computes a value for the 
other which will accommodate all of the data.

In this case, 0 is not a positive integer, so the number of rows is chosen to put all the fields in a single column.

2

You could use tr command as follows:

tr -s ' ' '\n' < infile

and here are other options to do that.

sed -e $'s/\s*/\\\n/g' infile

Or:

sed 's/\s*/\
/g' infile.txt

Or in some sed implementations, use:

sed 's/\s*/\n/g' infile

Or via gawk (if you don't mind last empty line):

awk -v RS='[[:blank:]]*' '1' infile

Or in bash:

#!/bin/bash
while read -r line; do 
    echo "${line// \+/$'\n'}";
done < infile

Or reading to an array and then printf:

#!/bin/bash
while read -a fields; do
    printf "%s\n" "${fields[@]}";
done < infile
1
$ tr ' ' '\n' <file.in

This will replace all spaces in the input file with newlines.

The result will be

2
3
4
5

(etc.)

To save the output to a file:

$ tr ' ' '\n' <file.in >file.out
1
awk '{ for(i=1;i<=NF;i++) print $i; }' input

or if blank lines shall be kept:

awk '/^$/ { print; }; { for(i=1;i<=NF;i++) print $i; }' input
3
  • Why do this approach don't has blank lines, unlike the approach with fold -1 file?
    – John Goofy
    Aug 28, 2017 at 0:30
  • @JohnGoofy I was not sure whether the blank lines were intentional thus I did not care about them. I edited my answer. Aug 28, 2017 at 10:25
  • Me too. But I was wondering why awk, respectively your approach, skips blank lines.
    – John Goofy
    Aug 28, 2017 at 10:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .