grep 无法搜索shell 传递过来的变量?

参考:https://www.cnblogs.com/yellow-hgy/p/10780578.html

 

#!/bin/sh

function scan_per_file()
{

SRC_FILE=$1
echo -e "\n${SRC_FILE}"
echo -e "\n${RESULT_FILE}"
cat ${CFG_FILE} |
while read api || [[ -n ${api} ]];
do
if [ "${api}" == "" ]; then
continue;
fi
#echo "${api}"
#grep -nr "TMGetName" ${SRC_FILE} > ${RESULT_FILE}
grep -rn "${api}" ${SRC_FILE} > ${RESULT_FILE}

done
}

CFG_FILE=`pwd`/mml.cfg
RESULT_FILE=`pwd`/FindIMml.res


scan_per_file $@

exit 0

 

 

一个脚本的知识点:

1、不要在window下写配置文件,在linux下去读的时候,换行符会变,可以使用cat -A 文件名 查看发现每行多了个^M$

          cat -A IMml.cfg
          TM_RegAndCancelCmd^M$

2、while read api || [[ -n ${api} ]]; 这语句作用是防止配置文件中最后一行没有换行符,导致直接结束while循环。 [[ -n ${api} ]] 表示缓冲区的内容不为空

3、if [ "${api}" == "" ];  if 的 "[  ]"是用来比较字符串的,[ 和test是等同的,可用的比较运算符只有==和!=,两者都是用于字符串比较的,比较数字用 ((i>4))

      [ ... ],它其实是一个程序 /usr/bin/[,相当于/usr/bin/test,后面多的那个]只是为了对称好看而已,所以[ 后面要有空格。

4、使用 -x 参数,可用调试,实际脚本运行情况

root@cdhw-VirtualBox:/home/code/shelldemo# bash -x ./FindMml.sh word.txt
++ pwd
+ CFG_FILE=/home/code/shelldemo/mml.cfg
++ pwd
+ RESULT_FILE=/home/code/shelldemo/FindIMml.res
+ scan_per_file word.txt
+ SRC_FILE=word.txt
+ echo -e '\nword.txt'

word.txt
+ echo -e '\n/home/code/shelldemo/FindIMml.res'

/home/code/shelldemo/FindIMml.res
+ read api
+ cat /home/code/shelldemo/mml.cfg
+ '[' TMGetName == '' ']'
+ grep -rn TMGetName word.txt
+ read api
+ '[' '' == '' ']'
+ continue
+ read api
+ [[ -n '' ]]
+ exit 0

posted @ 2020-05-14 01:00  ren_zhg1992  阅读(267)  评论(0)    收藏  举报