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

File Awk:从许多不同的文件中提取不同的列,file,awk,File,Awk,文件示例 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.556

文件示例

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
>
       ........
我需要从文件1中获取列1,从文件2中获取列3,从文件3中获取列7,从文件4中获取列1,并将它们并排合并到一个文件中

试用版1:不工作


粘贴剪切
和粘贴
的组合应该可以:

$ cat f1
foo
bar
baz
$ cat f2
1 2 3
4 5 6
7 8 9
$ cat f3
a b c d
e f g h
i j k l
$ paste -d' ' <(cut -f1 f1) <(cut -d' ' -f2 f2) <(cut -d' ' -f3 f3)
foo 2 c
bar 5 g
baz 8 k
$cat f1
福
酒吧
巴兹
$cat f2
1 2 3
4 5 6
7 8 9
$f3类
a、b、c、d
e f g h
i j k l

$paste-d'假设您的每个文件都有相同的行数,下面是使用
GNU awk
的一种方法。运行方式如下:

awk -f script.awk file1.txt file2.txt file3.txt file4.txt
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]
    }
}
FILENAME==ARGV[1]{one[FNR]=$1}
FILENAME==ARGV[2]{two[FNR]=$3}
FILENAME==ARGV[3]{three[FNR]=$7}
FILENAME==ARGV[4]{four[FNR]=$1}
结束{

对于(i=1;i在您的
粘贴
/
剪切
尝试中,将
剪切
替换为
awk

$ paste <(awk '{print $1}' file1 ) <(awk '{print $3}' file2 ) <(awk '{print $7}' file3) <(awk '{print $1}' file4)

$paste使用
cut
paste
如何不起作用?我认为这是因为cut假设间距是恒定的。我用不同的间距格式化数据,以便使数字在每列的左侧对齐。如果一个数字有更多的数字,其左侧的空格将更少。该示例有效,但仅适用于consISENT间距…我的问题有歧义,对不起。我的意思是文件本身的间距不一致。粘贴这正是我所需要的,快速且简单。干杯!是否可以将其推广到任意数量的输入文件(例如,从for循环)?+1个标题的真实答案。可能也是我问题的最佳答案。
awk -f script.awk file1.txt file2.txt file3.txt file4.txt
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]
    }
}
$ paste <(awk '{print $1}' file1 ) <(awk '{print $3}' file2 ) <(awk '{print $7}' file3) <(awk '{print $1}' file4)