Sean Nguyen
Sean Nguyen

Reputation: 13118

how to convert rows into column using awk?

I have an input contains of 36 lines like this:

822
526006
1343315205
1.4.2
32
0.000000
13.048815
...
0
0
0

That is the output from memcache stats command. So it is not from a file. How can I convert those lines into a columns of a single row. I don't want to use temp file.

Thanks,

Upvotes: 3

Views: 20497

Answers (6)

R J
R J

Reputation: 1954

In bash, you can use something like this.

input="822
526006
1343315205
1.4.2
32
0.000000
13.048815"

Then use a simple for loop.

for row in $(echo "$input");do echo -en "$row ";done;echo

Outputs

822 526006 1343315205 1.4.2 32 0.000000 13.048815

Note that last echo is to avoid having your prompt on the same line, remove if you use this in a script accordingly.

Upvotes: 0

Anuj
Anuj

Reputation: 9622

anuj@test:~$ cat num
1
2
3
4
5
anuj@test:~$ cat num |xargs
1 2 3 4 5
anuj@test:~$

cat and xargs would be more than enough i guess

Upvotes: 4

Levon
Levon

Reputation: 143037

Try this:

awk '{printf("%s ", $0)}'

using a pipe:

whatever_your_command | awk '{printf("%s ", $0)}'

The advantage of using printf() is that it gives you complete control over the output format/spacing/etc of your data.

--

Testing

822
526006
1343315205
1.4.2
32
0.000000
13.048815

data in file data.txt:

awk '{printf("%s ", $0)}' data.txt

yields:

822 526006 1343315205 1.4.2 32 0.000000 13.048815 

Upvotes: 10

slitvinov
slitvinov

Reputation: 5768

It can be a single character awk program

seq 10 | awk -v ORS=" " 1

Upvotes: 2

Igor Chubin
Igor Chubin

Reputation: 64563

You can do this without awk:

tr '\n' ' ' < file
echo $(<file)
xargs echo < file
perl -pe 's/\n/ /' < file

Example:

$ tr '\n' ' ' < data.txt
822 526006 1343315205 1.4.2 32 0.000000 13.048815
$ echo $(<data.txt)
822 526006 1343315205 1.4.2 32 0.000000 13.048815
$ xargs echo < data.txt
822 526006 1343315205 1.4.2 32 0.000000 13.048815
$ perl -pe 's/\n/ /' < data.txt
822 526006 1343315205 1.4.2 32 0.000000 13.048815

Upvotes: 6

jaypal singh
jaypal singh

Reputation: 77065

Using sed

input | sed ':a;N;{s/\n/ /};ba'

Upvotes: 1

Related Questions