【问题标题】:Write shell script to find content of one file into another and display all ocurrence编写 shell 脚本以将一个文件的内容查找到另一个文件中并显示所有出现
【发布时间】:2015-02-17 06:59:07
【问题描述】:

我需要编写一个 shell 脚本来将一个文件的内容[该文件的所有内容] 查找到另一个文件中,并在旁边显示内容的行号和出现的总数作为输出。

#!/bin/ksh
file="/home/ashish/contents.txt"

while read -r line; 
do
    grep $line /home/ashish/first.csv
done < "$file"

例如: 第一个文件包含此代码 “在 java.lang.Object.wait(Native Method) - 等待 (a weblogic.rjvm.ResponseImpl) 在 weblogic.rjvm.ResponseImpl.waitForData(ResponseImpl.java:76) - 锁定 (a weblogic .rjvm.ResponseImpl) " 第二个文件包含大量代码,所以我需要计算第二个文件中第一个文件中代码的出现次数 输出=第一个文件中的代码与行号一起出现在第二个文件中的次数(如果可能)。

【问题讨论】:

  • 请分享预期输出
  • bluefoggy:很清楚他需要什么。 @Ashish:我将分两步执行此操作:第一个脚本为 contents.txt 中的每个条目创建一个带有 grep 的更长脚本。之后可以自动删除。
  • 假设我们有两个文件,分别是 first 和 second,first 和 second 的内容如下: hello hi second : hi hello my name is ashish he said hi hello to her desired output should be 2 // 如果 first 在第二行 1 第 2 行中说明它出现的行号,则表示内容的出现
  • 请编辑您的问题并在那里显示预期的输出。
  • 第一个文件包含此代码“在 java.lang.Object.wait(Native Method) - 在 weblogic.rjvm.ResponseImpl.waitForData(ResponseImpl) 等待 (a weblogic.rjvm.ResponseImpl) .java:76) - 锁定 (a weblogic.rjvm.ResponseImpl) "第二个文件包含大量代码,所以我需要计算第二个文件中第一个文件中代码的出现次数输出=代码次数在第一个文件中出现在第二个文件中。

标签: linux bash shell unix ubuntu


【解决方案1】:

您可以简单地 grep 内容,并且可能会有重复的条目,所以最后只需将输出通过管道传输到 sort -usort | uniq

喜欢:

while read -r line;do  echo -n $(grep -c $line /home/ashish/first.csv); echo "  $line";done <"$file" | sort -u

grep -c 将计算出现次数 sort -u 将对输出进行唯一排序

【讨论】:

  • 我需要搜索多行,这只是搜索单行。我的意思是如果我必须在第二个文件中搜索多个字符串
猜你喜欢
  • 2021-04-24
  • 2010-11-08
  • 1970-01-01
  • 2013-09-06
  • 2018-10-05
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
相关资源
最近更新 更多