How can I write a shell script to go through all the sub-directories below a given directory and in each of those sub-directories search the file called "copyright" for strings like "license" or "GPL" and print the lines with those sub-strings. After running this I should be able to tell what the results were for each copyright file that was found.
3 Answers
Use find with -exec:
find . -name copyright -exec grep -H -e "license" -e "GPL" '{}' + >> results
Command
Using grep and Bash's ** (globstar, for deep expansion):
shopt -s globstar; # enable ** support
grep -i -E 'licence|GPL' **/copyright
Explanation
globstar:
If set, the pattern ** used in a pathname expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match.
-E,--extended-regexp:
Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)
References
- foo OR bar on the same line with grep ;
globstaroption (in Bash >=4)
3 Comments
globstar is available since Bash v4, but off by default. Hence the shopt -s globstar at the beginning. Otherwise use the solution given by @anubhavaHere's a sort of embarrassing script I use for producing a "License Report" for a FreeBSD host. I made it faster by switching out xargs for anubhava's -exec. Thanks!
#!/bin/sh
#
# pkg_license_check
#
# TODO: make this report on unlicensed packages.
#
LICENSES='MIT GPL ART BSD'
for LICENSE in $LICENSES
do
cd /usr/local/share/licenses
num=`find . -name LICENSE -exec grep -e "$LICENSE" '{}' + | wc -l`
echo "Total of $num $LICENSE Licensed packages as follows:"
find . -name LICENSE -exec grep -e "$LICENSE" -e '{}' + | awk -F":" '{sub("^\.\/", "", $1); print "\n" $1 "\n" $2 $3}'
echo -e "\n\n------------------------------------------------------------------------- \n\n"
done
A project for one day RSN: rewrite in perl and make "POSIX cross platform" for different packaging systems using plugins. :-)
findcommand withgrepcan do but I didn't fully understand the last point.awk,wcand friends to pull out the information you need. As I note below this may be a job forperland itsformattools ;-)