linux - 查找包含字符串的文件,但几个文件夹除外

标签 linux bash search grep find

我正在尝试查找一些文件,我已经为它编写了一个 bash 脚本并以这种方式使用它 - ./findme.sh "before",但效果不佳。有什么问题? 怎样改写正确,更美化?

#!/bin/bash
string=$1
clear
find . -name "*.*" ! -path "./node_modules" \
       ! -path "./bower_components" \
       ! -path "./public_lib/bootstrap" \
       ! -path "./public_lib/jquery" \
       ! -path "./public_lib/lib/bootstrap" \
       ! -path "./public_lib/lib/jquery" \
-print | xargs grep -o -r -n -C 3 --color=auto "$string" ./

echo "Search end!"
exit 0

最佳答案

您可以为此正确使用 grep:

#!/bin/bash
grep -rnC 3 --color=auto \
  --exclude-dir={node_modules,bower_components} \
  --exclude-dir=public_lib/{,lib/}{bootstrap,jquery} -- "$1" .

这将递归搜索所有文件以查找 $1 并显示行号和匹配项上下三行。

如果你想跟随符号链接(symbolic link),你应该使用 -R 而不是 -r

--exclude-dir={node_modules,bower_components} 使用大括号扩展并将扩展为:

--exclude-dir=node_modules --exclude-dir=bower_components

更高级的--exclude-dir=public_lib/{,lib/}{bootstrap,jquery},将扩展为:

--exclude-dir=public_lib/bootstrap --exclude-dir=public_lib/jquery \
--exclude-dir=public_lib/lib/bootstrap --exclude-dir=public_lib/lib/jquery

添加了反斜杠和换行符以进行说明。

关于linux - 查找包含字符串的文件,但几个文件夹除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37697978/

相关文章:

javascript - 是否有必要将css,js和图像放在django的静态文件夹中

python - 将 bash 参数传递给 python 脚本

linux - 使用 sed 的反向引用作为函数参数

linux - 在使 bash 脚本工作时遇到问题

PHP MySQL 按共同好友和国家/地区搜索用户

Javascript 正则表达式问题土耳其字符

linux - 如何在 curl 上指定 IP 地址?

bash - 使用 awk 为患者识别疾病

java - 如何在 Java 中使用 String 或 StringBuilder 倒序搜索?

linux - Nginx 重写规则而不改变 url