Bash 脚本来查找文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15177996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash Script to find files
提问by xlarsx
Good day, I've found an easy way to find files that have certain content, but I would like to create a bash script to do it quickier,
美好的一天,我找到了一种简单的方法来查找具有特定内容的文件,但我想创建一个 bash 脚本来更快地完成它,
The script is:
脚本是:
#!/bin/bash
DIRECTORY=$(cd `dirname .` && pwd)
ARGUMENTS="'$@'"
echo find: $ARGUMENTS on $DIRECTORY
find $DIRECTORY -iname '*' | xargs grep $ARGUMENTS -sl
So if I write:
所以如果我写:
$ script.sh text
It should find in that directory files that contains 'text'
它应该在该目录中找到包含“文本”的文件
But when I execute this script it always fails, but the echo command shows exactly what I need, what's wrong with this script?
但是当我执行这个脚本时它总是失败,但是 echo 命令正好显示了我需要的东西,这个脚本有什么问题?
Thank you!
谢谢!
Luis
路易斯
References: http://www.liamdelahunty.com/tips/linux_find_string_files.php
参考资料:http: //www.liamdelahunty.com/tips/linux_find_string_files.php
回答by jordanm
There are problems with quoting that will break in this script if either the current directory or the search pattern contains a space. The following is more simply, and fixes both issues:
如果当前目录或搜索模式包含空格,则引用问题将在此脚本中中断。以下更简单,并解决了这两个问题:
find . -maxdepth 1 -type f -exec grep "$@" {} +
With the proper quoting of $@, you can even pass options to grep, such as -i.
通过正确引用$@,您甚至可以将选项传递给 grep,例如-i。
./script -i "some text"
回答by Tuxdude
Try this version, with the following changes:
试试这个版本,有以下变化:
1.Use $1instead of $@unless you intend to run multiple find/grep to search for multiple patterns.
1.使用$1代替$@除非您打算运行多个 find/grep 来搜索多个模式。
2.Use find $DIR -type fto find all files instead of find $DIR -iname '*'
2.find $DIR -type f用于查找所有文件而不是find $DIR -iname '*'
3.Avoid piping by using the -execcommand line option of find.
3.通过使用-exec命令行选项避免管道find。
4.Do not single quote the command line arguments to your script, this was the main problem with the version you had. Your grep string had escaped single quotes \'search_string\'
4. 不要单引号给你的脚本的命令行参数,这是你的版本的主要问题。您的 grep 字符串已转义单引号\'search_string\'
#!/bin/bash
DIRECTORY=$(cd `dirname .` && pwd)
ARGUMENTS=""
echo find: $ARGUMENTS on $DIRECTORY
find $DIRECTORY . -type f -exec grep -sl "$ARGUMENTS" {} \;
There is no point extracting all the command line arguments and passing it to grep. If you want to search for a string with spaces, pass the string within single quotes from the command line as follows:
提取所有命令行参数并将其传递给grep. 如果要搜索带空格的字符串,请在命令行中将字符串放在单引号内,如下所示:
/home/user/bin/test-find.sh 'i need to search this'
回答by Srdjan Grubor
Why not just run the following?:
为什么不直接运行以下命令?:
grep -R text .

