我有一个与此问题类似的问题:How to do filtering of multiple files in a directory using awk?
上述问题答案中的解决方案对我不起作用。
我有制表符分隔的 txt 文件(全部位于 Observation_by_pracid 文件夹中)。对于每个文件,我想创建一个新文件,其中仅包含 $9 列 (medcodeid) 中具有特定值的行。具体值可以在medicalcode_list.txt中找到。 没有错误,但它只返回空文件。
代码列表
medcodeid
2576
3199
输入文件的格式
patid consid ... medcodeid
500470520002 3062539302 ... 2576
951924020002 3062538414 ... 310803013
503478020002 3061587464 ... 257619018
951924020002 3062537807 ... 55627011
503576720002 3062537720 ... 3199
所需输出
patid consid ... medcodeid
500470520002 3062539302 ... 2576
503576720002 3062537720 ... 3199
我的代码
mkdir HBA1C_observation_bypracid
awk '
NR==FNR {mlist[$1]; next }
FNR==1 {close(out); out="HBA1C_observation_bypracid/HBA1C_" FILENAME }
($9 in mlist) { print > out }
' PATH/medicalcode_list.txt *.txt
解决方案
mkdir HBA1C_observation_bypracid
awk '
BEGIN{ FS=OFS="\t" }
NR==FNR {mlist[$1]; next }
FNR==1 {close(out); out="HBA1C_observation_bypracid/HBA1C_" FILENAME }
($9 in mlist) { print > out }
' PATH/medicalcode_list.txt *.txt
添加“BEGIN...”解决了我的问题。
最佳答案
您可以使用 join
将两个文件连接到一列中。
文件必须按连接列排序。要对列执行数字
排序
,请使用这种方式排序,其中N
是列号:sort -kN -n FILE
您还需要获取每个文件的第一行(列名称)。您可以按以下方式使用 tail 命令,其中 N 是要输出内容的行数(因此第二行):
tail -n +N
...但仍然需要显示列值:
head -n 1 FILE
连接两个文件f1和f2,在f1的字段c1和f2的c2上,并输出文件x的字段y:
join -1 c1 -2 c2 f1 f2 -o "x.y, x.y"
工作示例:
head -n 1 input_file
for input_file in *.txt ; do
join -1 1 -2 9 -o "2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9" \
<(tail -n +2 PATH/medicalcode_list.txt | sort -k1 -n) \
<(tail -n +2 "$input_file" | sort -k3 -n)
done
结果(对于您提供的输入文件):
patid consid ... medcodeid
500470520002 3062539302 ... 2576
503576720002 3062537720 ... 3199
注意:列名称与值不一致。不知道有没有前提条件。您可以使用 printf
命令格式化显示。
关于awk - 使用 awk 过滤返回空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64124843/