How to Transfer the Data of Columns to Rows (With Awk)

How to transfer the data of columns to rows (with awk)?

This might work:

awk '{
for (f = 1; f <= NF; f++) { a[NR, f] = $f }
}
NF > nf { nf = NF }
END {
for (f = 1; f <= nf; f++) {
for (r = 1; r <= NR; r++) {
printf a[r, f] (r==NR ? RS : FS)
}
}
}' YOURINPUT

See it in action @ Ideone.

how to convert rows into column using awk?

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 

Collapsing a column value into lines, copying values of a second column

I would use GNU AWK following way. Contrived example to avoid superlong output, let file.txt be

col1 col2
5 1
3 0
5 1

then

awk 'NR>1{for(i=0;i<$1;i+=1)print $2}' file.txt

output

1
1
1
1
1
0
0
0
1
1
1
1
1

Explanation: I used for statement to print content of 2nd column ($2) times specified in 1st column ($1) for every line beyond 1st line (NR>1).

(tested in gawk 4.2.1)

How to copy a value from one column to another?

$ awk 'BEGIN{FS=OFS=","} (NR>1) && ($4!=""){$3=$4} 1' file
itemnumber,available,regprice,mapprice
00061,9,19.30,
00061030,31,3.19,3.19
00062,9,15.44,
00062410,2,3.99,3.99
00064,9,15.44,
00066850,29,3.99,3.99
00066871,49,5.99,5.99
00066878,3,7.99,7.99


Related Topics



Leave a reply



Submit