由于工作需要,需要在Linux环境下进行code的编写。当工程量大的时候,很难找出某个字段出现在那些文件中,因此写了一个shell脚本(文件名:search_tool.sh)进行字段的查找。如,需要查找src目录下含有字段"lht"的文件,及所在的行,只需执行命令:
search_tool.sh ./ lht
即可在当前文件夹中生成文件search_result,此文件中就包含了所有的查找结果。
如下为脚本文件的对应code:
#!/bin/sh
if [ $# != 2 ]
then
echo "error args num!"
exit 1
fi
dir=$1
ref=$2
if [ ! -d "$dir" ]
then
echo "dir doesn't exit!"
exit 1
fi
if [ -f "./search_result" ]
then
rm ./search_result
fi
touch search_result
echo "search for ref : $ref" >> ./search_result
echo >> ./search_result
for cur_file in $(find "$dir" -name "*.h" -o -name "*.cc" -o -name "*.c")
do
count_searched=$(grep -c "$ref" $cur_file)
if [ "$count_searched" != "0" ]
then
echo "<-----------------------$cur_file----------------------------->" >> ./search_result
grep -n "$ref" $cur_file >> ./search_result
echo >> ./search_result
fi
done
exit 0