web服务器
技术随笔
Linux 下 find 与 grep 组合查找文件内容(含多条件与排除)
在 Linux 下排查代码时,常把 find 和 grep 组合使用。下面整理常见用法与多条件过滤技巧。
一、find + grep 查找含关键字的文件
find /PATH -name "*.php"
find /PATH -name "*.php" -exec grep -in "helloworld" {} ;
find /PATH -name "*.php" | xargs grep -in "helloworld"
带 -exec 时必须以 ; 结尾,否则报“遗漏 -exec 的参数”。
二、find 多条件 / 排除
find /PATH ( -name "*.php" -or -name "*.c" ) -exec grep -in "hello" {} ;
find /PATH ( -not -name "*~" ) -exec grep -in "hello" {} ;
find . -type f ! -path '*/.svn/*'
三、grep 过滤 svn 目录
grep -r 'function_name' * | grep -v '.svn' grep -r --exclude-dir=.svn 'function_name' *
四、find 常用选项
find ~ -name "*.txt" -print
find ~ -perm 755 -print # 权限查找
find ~ -mtime -5 -print # 5天内修改
find ~ -type d -print # 只找目录
find ~ -size +1000000c -print # 大于 1MB
find . -name core -exec rm {} ; # 找到即删除
五、grep 多条件
grep -E '123|abc' file # 或 grep '123' file | grep 'abc' # 与 grep -i pattern file # 忽略大小写 grep -l pattern file # 只列文件名 grep -w pattern file # 整词匹配 grep -C 3 pattern file # 显示上下文各 3 行