Awk:从许多不同的文件中提取不同的列

ast*_*ada 4 awk file

文件示例

I have a 3-10 amount of files with:

 - different number of columns
 - same number of rows
 - inconsistent spacing (sometimes one space, other tabs, sometimes many spaces) **within** the very files like the below


>      0    55.4      9.556E+09   33
>      1     1.3      5.345E+03    1
>        ........
>     33   134.4      5.345E+04  932
>
       ........
Run Code Online (Sandbox Code Playgroud)

我需要从file1获取列(例如)1,从file2获取第3列,从file3获取第7列,从file4获取第1列,并将它们并排放入单个文件中.

试验1:不工作

paste <(cut -d[see below] -f1 file1) <(cut -d[see below] -f3 file2) [...]
Run Code Online (Sandbox Code Playgroud)

分隔符是'或空的.

试用版2:使用2个文件但不使用多个文件

awk '{
     a1=$1;b1=$4;
     getline <"D2/file1.txt";
     print a1,$1,b1,$4
}' D1/file1.txt >D3/file1.txt
Run Code Online (Sandbox Code Playgroud)

现在更一般的问题:

如何从许多不同的文件中提取不同的列?

mou*_*iel 19

在您的paste/ cut尝试中,替换cutawk:

$ paste <(awk '{print $1}' file1 ) <(awk '{print $3}' file2 ) <(awk '{print $7}' file3) <(awk '{print $1}' file4)
Run Code Online (Sandbox Code Playgroud)


Ste*_*eve 7

假设您的每个文件具有相同的行数,这是使用的一种方式GNU awk.运行如下:

awk -f script.awk file1.txt file2.txt file3.txt file4.txt
Run Code Online (Sandbox Code Playgroud)

内容script.awk:

FILENAME == ARGV[1] { one[FNR]=$1 }
FILENAME == ARGV[2] { two[FNR]=$3 }
FILENAME == ARGV[3] { three[FNR]=$7 }
FILENAME == ARGV[4] { four[FNR]=$1 }

END {
    for (i=1; i<=length(one); i++) {
        print one[i], two[i], three[i], four[i]
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:

默认情况下,awk分隔空格上的列.这包括制表符和空格,以及任何数量的这些.这awk适用于间距不一致的文件.如果您愿意,还可以展开上面的代码以包含更多文件.