0

I have a space delimited data out from a program in horizontal:

0 2 32 323 443 ...

I created a shell script to convert horizontal listed file to vertical to sort it out :

filename=/tmp/vList
colcount=$(wc -w < "$1")
counter=1
sortResult=0

while [ "$counter" -le "$colcount" ] do cat "$1" | cut -d " " -f"$counter">>"$filename" counter=$((counter+1)) done

It worked, however it creates a vertical list including blank lines between each values of the horizontal list:


0

2

32

323

Why are there blank lines, how can I prevent them?

[Edit] After IsaaC's suggestion, I saw that my question is duplicate of previous one, similar,even same answers were there, so I must close this question. I am appreciated to all contributors.

terdon
  • 242,166
  • 1
    What is the contents of the "$1" file? If it has blank/non-matched line then that could be what you're seeing. Also, you can replace the whole counter=$((counter+1)) with just ((counter++)). – CR. Mar 13 '22 at 21:28
  • 2
    Is there a blank line in your input file? Is it the 1st line? Side note: the script reads its input multiple times, this is far from optimal. – Kamil Maciorowski Mar 13 '22 at 21:29
  • @CR $1 file content is the list of the data as I wrote in question; for instance 02 32 232 323 ... –  Mar 13 '22 at 21:29
  • @KamilMaciorowski : YES ! Thanks, exactly the first line was blank. Thanks that solved. How can I improve multiple read issue? Do you means storing it to a variable? –  Mar 13 '22 at 21:32
  • 3
    You can achieve the same thing with simply cat inputlist.txt | tr ' ' '\n' > /tmp/vList. No multiple reads. No need for a script with a loop at all. – frabjous Mar 13 '22 at 21:36
  • 3
    @frabjous Leave the cat alone. :) <inputlist.txt tr … – Kamil Maciorowski Mar 13 '22 at 21:36
  • @KamilMaciorowski LOL. Gotta get out of that habit. Go ahead and give me the "useless use of cat award". – frabjous Mar 13 '22 at 21:37
  • Inspect your file for trailing blanks: od -bc /tmp/vList – waltinator Mar 13 '22 at 22:39

4 Answers4

1

You can do this with tr:

tr ' ' '\n' < file

For example:

% cat file
0 2 32 323 443
% tr ' ' '\n' < file
0
2
32
323
443
Chris Down
  • 125,559
  • 25
  • 270
  • 266
0

Are you sure it's a pure shell script you want?

grep -o '\S\+' input.file

or

sed 's/[[:blank:]\n]\+/\n/g' input.file

or

awk -v RS='([[:blank:]\n]+)' '1' input.file

or

awk '{ for(i=1;i<=NF;i++) print $i }' input.file

...is probably more accurate.

0
perl -pne "s/ /\n/g" filename

output

0
2
32
323
443
-1

A better way:

#!/bin/bash
filename="/tmp/vList"
for i in $(cat "$filename") ; do
    echo "$i"
fi
waltinator
  • 4,865