简体   繁体   English

从文件中以bash打印n到n列

[英]print n to n columns in bash from a file

I have thousands of columns delimited by whitespace. 我有成千上万的空格分隔的列。 I want to do something similar to 我想做类似的事情

awk '{print$1" "$2}' file

but I need to print a range and maintain the space between them. 但是我需要打印一个范围并保持它们之间的间距。

For example is I have a file with the contents: 例如,我有一个包含内容的文件:

1.006 2.0101 1.002 3.005 0.0000 4.09873 9.0009 1000.678 15.0 0.9999 11.8
78.003 9.411 0.000 0.003 20000.0100 1.03 9.00029 100.0 0.5 123.9 1.800

and I want to print columns 2-3 and 6-9 I would get: 我想打印第2-3和6-9列,我会得到:

2.0101 1.002 4.09873 9.0009 1000.678 15.0
9.411 0.000 1.03 9.00029 100.0 0.5

I am open to other tools but this seems like a good one-liner in awk. 我对其他工具持开放态度,但这似乎是awk中的一个好工具。

如果每个字段之间有一个空格,则cut是适合该作业的工具:

cut -d' ' -f 2-3,6-9 file

Actually cut is right tool, current context its the best way to handle your job, but still if you need awk , you may try something like this : 实际上, cut是正确的工具,当前上下文是处理工作的最佳方法,但是仍然需要awk ,您可以尝试如下操作:

$ cat ext_f.awk 
function ext_field(s,e, r,i)
{   if(e > s)
    {
        for(i=s; i<=e; i++)r = i > s ? r OFS $i : $i;
    }else{
        if(s!="")return $s
    }
    return r
}
{ print ext_field(2,3), ext_field(6,9) }

Execution : 执行:

Input : 输入:

$ cat file
1.006 2.0101 1.002 3.005 0.0000 4.09873 9.0009 1000.678 15.0 0.9999 11.8
78.003 9.411 0.000 0.003 20000.0100 1.03 9.00029 100.0 0.5 123.9 1.800

Output : 输出:

$ awk -f ext_f.awk file
2.0101 1.002 4.09873 9.0009 1000.678 15.0
9.411 0.000 1.03 9.00029 100.0 0.5

Suppose if you need comma or some other char as output separator, then you may modify -v OFS= like below 假设如果需要逗号或其他字符作为输出分隔符,则可以如下所示修改-v OFS=

$ awk -v OFS="," -f ext_f.awk file
2.0101,1.002,4.09873,9.0009,1000.678,15.0
9.411,0.000,1.03,9.00029,100.0,0.5

If you have gawk then just remove below lines, from ext_f.awk , and use --source option 如果您有gawk则只需从ext_f.awk删除以下ext_f.awk ,然后使用--source选项

{ print ext_field(2,3), ext_field(6,9) }

Example : 范例:

$ awk -v OFS="," -f ext_f.awk --source '{print ext_field(1,2)}' file
1.006,2.0101
78.003,9.411

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM