Created
December 13, 2015 12:18
-
-
Save peco8/635257a94be008a1a3ff to your computer and use it in GitHub Desktop.
Find file in current directory recursively, and print lines which match PATTERN.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
usage() | |
{ | |
# Fetch the shell script name | |
local script_name=$(basename "$0") | |
# Show help | |
cat << END | |
Usage: $script_name PATTERN [PATH] [NAME_PATTERN] | |
Find file in current directory recursively, and print lines which match PATTERN. | |
PATH find file in PATH directory, instad of current directory | |
NAME_PATTERN specify name pattern to find file | |
Examples: | |
$script_name return | |
$script_name return ~'*.txt' | |
END | |
} | |
# If failts to fetch any arguments | |
if [ "$#" -eq 0 ]; then | |
usage | |
exit 1 | |
fi | |
pattern=$1 | |
directory=$2 | |
name=$3 | |
# If 2nd argument is empy, set currenty directory | |
if [ -z "$directory" ]; then | |
directory='.' | |
fi | |
# If 3rd argument is empy, set '*' | |
if [ -z "$name" ]; then | |
name='*' | |
fi | |
# If the directory you specified is nowhere, comes out the error, and exit | |
if [ ! -d "$directory" ]; then | |
echo "$0: ${directory}: No such directory" 1>&2 | |
exit 2 | |
fi | |
find "$directory" -type f -name "$name" | xargs grep -nH "$pattern" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment