linux - 用于在文件列表中查找单词的 shell 脚本,所有文件都作为参数给出

标签 linux bash shell

我需要一个简单的 shell 程序,它必须执行如下操作:

script.sh word_to_find file1 file2 file3 .... fileN

将显示

word_to_find 3 - if word_to_find appears in 3 files

word_to_find 5 - if word_to_find appears in 5 files 

这是我试过的

#!/bin/bash

count=0
for i in $@; do
  if [ grep '$1' $i ];then
     ((count++))
  fi
done
echo "$1 $count"

但是这个消息出现了:

syntax error: "then" unexpected (expecting "done").

在此之前错误是

[: grep: unexpected operator.

最佳答案

试试这个:

#!/bin/sh
printf '%s %d\n' "$1" $(grep -hm1 "$@" | wc -l)

注意脚本的所有参数是如何逐字传递给 grep 的——第一个是搜索表达式,其余是文件名。

grep -hm1 的输出是一个匹配列表,每个文件一个匹配,wc -l 对它们进行计数。

我最初使用 grep -l 发布了这个答案,但是这要求文件名永远不包含换行符,这是一个相当讨厌的限制。

如果不需要正则表达式搜索(即只搜索文字文本),可以添加一个 -F 选项。

关于linux - 用于在文件列表中查找单词的 shell 脚本,所有文件都作为参数给出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322577/

相关文章:

linux - 使文件对库函数显示为只读

linux - linux-2.6.38.1.tar.xz、linux-2.6.38.2.tar.xz等文件名中 'linux-2.6.38.'后面的数字是什么意思?

bash - 在 Bash 中提取文件名和扩展名

linux - 如何避免由于套接字文件导致的Linux移动错误?

shell - 提取最后一行第n列的值

linux - 编写一个运行程序的 shell 脚本,模拟用户对程序的输入

python - 使用 subprocess call/popen 从另一个 python 脚本执行 python 脚本

c++ - 如何安装依赖libstdc++库的程序

linux -/usr/bin/ld : skipping incompatible foo. 所以在搜索 foo 时

xcode - 打开 Xcode 项目并从终端设置事件文件