Skip to content

Instantly share code, notes, and snippets.

@peco8

peco8/file_finder.sh

Created Dec 13, 2015
Embed
What would you like to do?
Find file in current directory recursively, and print lines which match PATTERN.
#!/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