连接多个没有标题的文件
我有几个目录(“amazon”,“niger”,…),其中我有几个子目录(“gfdl”,“hadgem”,…),其中我也有几个子目录(“rcp8p5” “,”rcp4p5“,…)。 在这最后的子目录中,我总是有两个文件夹(“历史”,“投影”),其中包含数千个具有相同框架的表。 因此,我想连接这些表(存在于最后一个子目录的两个文件夹中),以便每次只有一个表连接时,只有一个大表只有一个头而不是头。 有谁知道怎么做?
我目前正在使用以下循环结构:
#!/bin/bash # usage:cat_dat dirname data_dir=/scratch/01/stevens/climate_scenario/river for river in tagus do for gcm in gfdl-esm2m hadgem2-es do for scenario in rcp8p5 rcp4p5 rcp6p0 rcp2p6 do find "${data_dir}/${river}/${gcm}/${scenario}" name \*.dat -exec cat {} + >> "${data_dir}/${river}/${gcm}/${scenario}.dat" done done done
但我无法摆脱那个标题! 非常感谢任何帮助! 谢谢!
在单个文件夹中使用awk
awk 'NR==1 {header=$_} FNR==1 && NR!=1 { $_ ~ $header getline; } {print}' *.dat > out
如果您需要当前文件夹和子文件夹中的所有文件,请find
并使用awk
。 你可以替换.
与您想要的文件夹。
find . -type f -name "*.dat" -print0 | \ xargs -0 awk 'NR==1 {header=$_} FNR==1 && NR!=1 { $_ ~ $header getline; } {print}' > out
或者,因为getline很糟糕 (thx @fedorqui )
find . -type f -name "*.dat" -exec awk 'NR==1 || FNR!=1' {} + ;
例
% cat foo1.dat abc 1 2 3 % cat foo2.dat abc 4 5 6 % awk 'NR==1 {header=$_} FNR==1 && NR!=1 { $_ ~ $header getline; } {print}' *.dat > out % cat out abc 1 2 3 4 5 6
您可以使用while
循环通过进程替换 find
:
d=0 while IFS= read -r file do [ "$d" -ge 1 ] && tail -n +2 "$file" || cat "$file" (( d ++ )) done < <(find "/dir/folder" name *.dat)
因此它将在第一场比赛中执行一只cat
,并在其余部分tail -n +2
。
或者,如果您拥有同一目录中的所有文件,您可以说:
awk 'FNR>1 || NR==1' files*
这将匹配除FNR==1
和NR>1
,即除了第一个之后的文件头之外的所有内容。 为什么? 因为NR
保持整体读取的行数,而FNR
保持正在读取的当前文件的行数。