How to format the data of a file in Unix?

試著忘記壹切 提交于 2019-12-11 16:46:25

问题


I have some data in this form (3 columns) stored in the variable ABC:

d1  d2 d3 
d4 d5 d6 
d7 d8 d9 
d10 

and I would like to format it in this form (4 columns):

d1 d2 d3 d4 
d5 d6 d7 d8
d9 d10

I've tried something like this:

printf "%8.3e %8.3e %8.3e %8.3e\n" "${ABC}"

but it doesn't work. Can anyone see where the problem is?


回答1:


So you have a file with a content like this:

d1 d2 d3
d4 d5 d6
d7 d8 d9
d10

and you want to convert it into

d1 d2 d3 d4
d5 d6 d7 d8
d9 d10

That is, convert it from 3 columns per line into 4.

For this you can use xargs like:

xargs -n 4 < file

Or, if the data is in a variable:

xargs -n 4 <<< "$variable"

From man xargs

-n max-args, --max-args=max-args

Use at most max-args arguments per command line.

Test

$ cat a
1 2 3
4 5 6
7 8 9
10
$ xargs -n 4 < a
1 2 3 4
5 6 7 8
9 10


来源:https://stackoverflow.com/questions/28326597/how-to-format-the-data-of-a-file-in-unix

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