【问题标题】:Count number of occurences using awk on large files在大文件上使用 awk 计算出现次数
【发布时间】:2013-04-15 10:18:03
【问题描述】:

我有 2 个文件。首先有很少的记录也存在于 file2 中。文件 2 大于文件 1。我想在 file2 显示单词的出现次数(来自 file1)。

这是我尝试过的

file1.txt
bash-3.00# cat file1.txt |wc -l
17102666

more file1.txt
123advertise3
123advertise4
123advertise5
123advertiseb
123advertisec
123advertised
123advertisedebtconsolidation
123advertisee
123advertisef
123advertiseg
123advertiseh
123advertisehomaxproducts

文件2

file2.txt
bash-3.00#cat file2.txt | wc -l
113842500


more file2.txt
123123apartment
123123attorney
123123auction
123123auto
123advertisedebtconsolidation
123advertiseb
123123automate
123123automatic
123123bank
123advertisedebtconsolidation
123advertiseb
123123banking
123123bankruptcy
123advertisedebtconsolidation
123123bargain
123123best
123123blog
123advertisedebtconsolidation
123123building

我想要这样的输出

123advertisedebtconsolidation 3
123advertiseb 2

我在命令下运行

bash-3.00# nawk 'FNR==NR{c[$1];next}$1 in c{++c[$1]}END{for(i in c) print i,c[i]}' file1.txt file2.txt

但我没有得到想要的输出。

我只有字符串之类的东西

peaktablethomecsuchico
browsepropertyhomebase
clickflowershomedsn
worldwideflowerstravelagency
acepigb
acepigc
browsecompanytravelagent
liveearnhomedownpaymentassistance
acepigd
bargainsystemhomebvcure
acepige
acepigf
uniquecasinohomecycling
alternativeanyhomecanningrecipes
acepigj
annualsurveyhomedma

谁能帮助我在更大的文件中使用 grep 或 awk 获得这样的输出。我在较小的文件上尝试了同样的方法,效果很好。

【问题讨论】:

  • 我执行了您给出的相同命令。并且它按预期工作。不知道为什么它不能在你的最后工作

标签: linux shell


【解决方案1】:

uniq 命令可能是一种输出常用字符串的简单方法。 -c 选项指定输入中的匹配数。 awk 命令仅输出出现多次的行。

cat file1.txt file2.txt | sort | uniq -c | awk '{ if ($1 > 1) print $0; }'

【讨论】:

  • 但我想看看 word(来自 file1)出现在 file2 的次数。
  • 我正在尝试。如您所见,文件很大,因此需要时间来显示结果。有什么办法可以更快地完成这项工作吗?
  • 我看到您只打印了多次出现的字符串,但我也想显示出现次数以及字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 2017-05-25
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多