简体   繁体   中英

Bash Script to find files

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,

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?

Thank you!

Luis

References: http://www.liamdelahunty.com/tips/linux_find_string_files.php

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 .

./script -i "some text"

Try this version, with the following changes:

1.Use $1 instead of $@ unless you intend to run multiple find/grep to search for multiple patterns.

2.Use find $DIR -type f to find all files instead of find $DIR -iname '*'

3.Avoid piping by using the -exec command line option of 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\\'

#!/bin/bash
DIRECTORY=$(cd `dirname .` && pwd)
ARGUMENTS="$1"

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:

/home/user/bin/test-find.sh 'i need to search this'

为什么不运行以下?:

grep -R text .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM