Convert n number of rows to columns repeatedly using awk

跟風遠走 提交于 2020-01-05 08:32:28

问题


My data is a large text file that consists of 12 rows repeating. It looks something like this:

{
1
2
3
4
5
6
7
8
9
10
}

repeating over and over. I want to turn every 12 rows into columns. so the data would look like this:

{ 1 2 3 4 5 6 7 8 9 10 }
{ 1 2 3 4 5 6 7 8 9 10 }
{ 1 2 3 4 5 6 7 8 9 10 }

I have found some examples of how to convert all the rows to columns using awk: awk '{printf("%s ", $0)}', but no examples of how to convert every 12 rows into columns and then repeat the process.


回答1:


You could use something like this:

awk '{printf "%s%s", $0, (NR%12?OFS:RS)}' file

NR%12 evaluates to true except when the record number is exactly divisible by 0. When it is true, the output field separator is used (which defaults to a space). When it is false, the record separator is used (by default, a newline).

Testing it out:

$ awk '{printf "%s%s", $0, (NR%12?OFS:RS)}' file
{ 1 2 3 4 5 6 7 8 9 10 }



回答2:


Here is an idiomatic way (read golfed down version of Tom Fenech's answer) of doing it with awk:

$ awk '{ORS=(NR%12?FS:RS)}1' file
{ 1 2 3 4 5 6 7 8 9 10 }
{ 1 2 3 4 5 6 7 8 9 10 }
{ 1 2 3 4 5 6 7 8 9 10 }

ORS stands for Output Record Separator. We set the ORS to FS which by default is space for every line except the 12th line where we set it to RS which is a newline by default.



来源:https://stackoverflow.com/questions/25901381/convert-n-number-of-rows-to-columns-repeatedly-using-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!