我正在尝试遍历文件夹,在每个文件上运行grep,并将它们放入单独的文件中,标记为.res
扩展名。这是我到目前为止所拥有的......
#!/bin/bash
directory=$(pwd)
searchterms="searchterms.txt"
extension=".end"
usage() {
echo "usage: fmat [[[-f file ] [-d directory ] [-e ext]] | [-h]]"
echo " file - text file containing a return-delimited list of materials"
echo " directory - directory to process"
echo " ext - file extension of files to process"
echo ""
}
while [ "$1" != "" ]; do
case $1 in
-d | --directory ) shift
directory=$1
;;
-f | --file ) shift
searchterms=$1
;;
-e | --extension ) shift
extension=$1
;;
-h | --help ) usage
exit
;;
* ) usage
exit 1
esac
shift
done
if [ ! -d "$directory" ]; then
echo "Sorry, the directory '$directory' does not exist"
exit 1
fi
if [ ! -f "$searchterms" ]; then
echo "Sorry, the searchterms file '$searchterms' does not exist"
exit 1
fi
echo "Searching '$directory' ..."
for file in "${directory}/*"; do
printf "File: %s\n" ${file}
[ -e "$file" ] || continue
printf "%s\n" ${file}
if [ ${file: -3} == ${extension} ]; then
printf "%s will be processed\n" ${file}
#
# lots of processing here
#
fi
done
我知道这是由于我对全球化的理解不足......但我无法对扩展工作进行测试。
基本上,我希望能够指定源目录,包含搜索词的文件以及要搜索的扩展名。
现在,我意识到可能有更快的方法来做到这一点,例如。
grep -f searchterms.txt *.end > allchanges.end.res
但是我可能还需要对文件进行其他处理,我想将它们保存到单独的文件中:所以bing.end,bong.end将会变成bing.end.res,bong。 end.res。
请让我知道,我是多么愚蠢; - )
为了完整起见,这是最后一部分,工作,感谢@chepner和@Gordon Davisson:
echo "Searching '$directory' ..."
for file in "${directory}"/*; do
[ -e "$file" ] || continue
# show which files will be processed
if [[ $file = *.${extension#.} ]]; then
printf "Processing %s \n" "$file"
head -n 1 "${file}" > "${file}.res"
grep -f $searchterms "${file}" >> "${file}.res"
fi
done
答案 0 :(得分:3)
您只需要将*
从引号中删除,这样它就不会被视为文字*
:
for file in "${directory}"/*; do
与大多数语言不同,引号不定义字符串(因为bash
中的所有内容都是字符串:它是唯一的数据类型)。他们只是逃避引号内的每个字符。 "foo"
与\f\o\o
完全相同,因为(因为逃避大多数字符实际上没有任何效果)与foo
相同。引用与否,所有未被分词符号分隔的字符都是同一个单词的一部分。
http://shellcheck.net会抓住这个,尽管没有最有用的错误消息。 (它还会捕获您没有引用但应该引用的其他参数扩展。)