简体   繁体   中英

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.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.

如果每个字段之间有一个空格,则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 :

$ 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

$ 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

{ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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