簡體   English   中英

使用 awk 計算另一個文件中模式出現的次數

[英]using awk to count the number of occurrences of pattern from another file

我正在嘗試獲取一個包含列表的文件並計算該列表中的項目在目標文件中出現的次數。 就像是:

list.txt
blonde
red
black

target.txt
bob blonde male
sam blonde female

desired_output.txt
blonde 2
red 0
black 0

我選擇了以下代碼來獲取存在於 target.txt 中的值:

awk '{count[$2]++} END {for (word in count) print word, count[word]}' target.txt

但是輸出不包括在 liist.txt 但不包括在 target.txt 中的所需項目

current_output.txt
blonde 2

我已經嘗試了一些事情來讓這個工作,包括:

awk '{word[$1]++;next;count[$2]++} END {for (word in count) print word, count[word]}' list.txt target.txt

但是,我沒有成功。

任何人都可以幫助我使這個 awk 語句讀取 key.txt 文件嗎? 對代碼的任何解釋也將不勝感激。 謝謝!

awk '
  NR==FNR{a[$0]; next}
  {
    for(i=1; i<=NF; i++){
      if ($i in a){ a[$i]++ }
    }
  }
  END{
    for(key in a){ printf "%s %d\n", key, a[key] }
  }
' list.txt target.txt
  • NR==FNR{a[$0]; next} NR==FNR{a[$0]; next}條件NR==FNR僅適用於第一個文件,因此數組a的鍵是list.txt行。

  • for(i=1; i<=NF; i++)現在對於第二個文件,這將遍歷其所有字段。

    • if ($i in a){ a[$i]++ }這檢查字段$i是否作為數組a的鍵存在。 如果是,則與該鍵關聯的值(初始為零)遞增。
  • END ,我們只打印key然后是出現次數a[key]和換行符 ( \\n )。

輸出:

blonde 2
red 0
black 0

筆記:

  1. 由於%dprintf語句強制將a[key]轉換為整數,以防它仍未設置。 整個語句可以替換為更簡單的print key, a[key]+0 我在寫答案時錯過了這一點,但現在您知道做同一件事的兩種方法。 ;)

  2. 在您的嘗試中,出於某種原因,您只處理字段 2 ( $2 ),而忽略了其他列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM