Sunday, May 5, 2024
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 1942  / 1 Year ago, mon, april 10, 2023, 10:23:29

I have a tab-separated data like this:



a 2
b 3
c 4
d 6
e 8
f 9
g 10
h 11
i 12
...


My desired output should look like this:



a 2 d 6 g 10 
b 3 e 8 h 11
c 4 f 9 i 12


How can I do this, for instance using awk.



Thanks in advance.
Sincerely,
nsingh


More From » command-line

 Answers
7

Using awk:



$ awk '{a[FNR%3] = a[FNR%3] == "" ? $0 : a[FNR%3] "	" $0} END{for(i=1;i<=3;i++) print a[i%3]}' data.tsv
a 2 d 6 g 10
b 3 e 8 h 11
c 4 f 9 i 12


Another possibility is the rs utility - probably not installed by default, but available on Ubuntu from package rs.



$ rs -e -C -t 0 3 < data.tsv
a 2 d 6 g 10
b 3 e 8 h 11
c 4 f 9 i 12


where




  • -e treat each input line as an array element

  • -C output columns separated by a single tab

  • -t transpose input columns to rows

  • 0 3 use as many rows as necessary with 3 columns



Another option is the pr command



Ex. print in 3 columns, suppressing headers and footers:



$ pr -T -3 < data.tsv
a 2 d 6 g 10
b 3 e 8 h 11
c 4 f 9 i 12


If you want the columns separated by exactly one TAB character:



$ pr -s$'	' -T -3 < data.tsv
a 2 d 6 g 10
b 3 e 8 h 11
c 4 f 9 i 12

[#3878] Wednesday, April 12, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tersle

Total Points: 342
Total Questions: 109
Total Answers: 99

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;