从多个文件中获取字符串并复制到新文件并将文件名打印到 bash 中的第二列

Take string from multiple files and copy to new file and print filename into second column in bash

我有多个包含此信息的文件:

sP12345.txt

COMMENT     Method: conceptual translation.
FEATURES             Location/Qualifiers
     source          1..3024
                     /organism="H"
                     /isolate="sP12345"
                     /isolation_source="blood"
                     /host="Homo sapiens"
                     /db_xref="taxon:11103"
                     /collection_date="31-Mar-2014"
                     /note="genotype: 3"

sP4567.txt

COMMENT     Method: conceptual translation.
FEATURES             Location/Qualifiers
     source          1..3024
                     /organism="H"
                     /isolate="sP4567"
                     /isolation_source="blood"
                     /host="Homo sapiens"
                     /db_xref="taxon:11103"
                     /collection_date="31-Mar-2014"
                     /note="genotype: 2"

现在我想获取 /note="genotype: 3" 并仅复制 genotype: 之后的数字,将其复制到新的文本文件并打印已作为第 2 列的文件名。

预期输出:

3  sP12345
2  sP4567

我试过这段代码:但它只打印第一列而不是文件名:

awk -F'note="genotype: ' -v OFS='\t' 'FNR==1{++c} NF>1{print , c}' *.txt > output_file.txt
$ awk -v OFS='\t' 'sub(/\/note="genotype:/,""){print [=10=]+0, FILENAME}' sP12345.txt sP4567.txt
3       sP12345.txt
2       sP4567.txt

你可以这样做:

awk '/\/note="genotype:/{split([=10=],a,": "); print a[2]+0,"\t",FILENAME}' sP*.txt 
3    sP12345.txt
2    sP4567.txt

您可以使用:

awk '/\/note="genotype: /{gsub(/^.* |"$/, ""); f=FILENAME; sub(/\.[^.]+$/, "", f); print [=10=] "\t" f}' sP*.txt

3   sP12345
2   sP4567

使用 GNU awk 中显示的示例,请尝试以下 awk 代码。

awk -v RS='/note="genotype: [0-9]*"' '
RT{
  gsub(/.*: |"$/,"",RT)
  print RT,FILENAME
  nextfile
}
' *.txt

解释: 简单的解释就是,在这里将所有 .txt 文件传递​​给 GNU awk 程序。然后根据显示的示例和要求将 RS(记录分隔符)设置为 /note="genotype: [0-9]*"。在 awk 的主程序中,使用 gsub(全局替换)删除所有内容,直到冒号后跟 space AND " 在 RT 值的末尾带有 NULL。然后打印 RT 的值,后跟当前文件的名称。使用 nextfile 将跳过文件的其余内容直接将程序带到下一个文件,为我们节省一些时间。