- Shell script that searches through all files in a specified directory (recursively) for occurrences of a given string e.g.
FOOBAR. - This script can be customized by changing the
SEARCH_STRINGvariable. - The script uses
grepto find the string and ignores binary files usingfile -I.
- Save the script in a file, for example,
search_string.sh. - Make it executable with the command
chmod +x search_string.sh. - Run the script from the terminal by providing the directory you want to search in as an argument. For example:
./search_string.sh /path/to/directory
- If no path is provided, it defaults to the current directory (
.).
SEARCH_STRINGholds the string you want to search for in all files under a specific directory. You can change this to any other term or use command line argument to pass it dynamically.SEARCH_DIR=${1:-"."}allows you to specify the directory to be searched without hardcoding it into the script, using the first argument provided to the script ($1). If no argument is given, it defaults to the current directory (.).grep -rIflag means:-r: Recursively search through directories.-I: Ignore binary files because grep would normally find them and you get confusing output.--exclude='*.o', etc.: These are patterns to exclude specific file types, which are common compiled object files that might clutter the results (depending on your project). You can adjust or expand these excludes as needed for your use case.
- The script uses
file -Iimplicitly when runninggrepto filter out binary files, though this is not explicitly mentioned in the script above. If you have older versions of grep that don't support-I, you might need to adjust or replace it with a different approach to exclude binaries based on file content detection (which would be less efficient and more complex).
This script should work well for searching through text files where your string might appear, such as source code in programming languages. Adjust the search patterns (--exclude flags) if you need to broaden or narrow the scope of what is included or excluded from the search.