我正在尝试编写一个bash脚本,该脚本将查找包含特定字符串的文件。该脚本调用另一个返回格式字符串的脚本:
url=title
title
是我要找的字符串。title
可以有如下所示的值,例如:'A Soldier Of The Legion'
。我试图在
/tmp/audiobooks
目录中找到包含标题'A Soldier Of The Legion'
的文件。/tmp/audiobooks
中的所有文件的名称都以AB.yaml
结尾。这是剧本:
#!/bin/sh
get_pairs='/home/me/util/scripts/get-pairs.sh'
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for i in `$get_pairs`
do
echo "pair $i"
url=`echo $i | cut -d= -f1`
apptitle=`echo $i | cut -d= -f2- | cut -c1-52`
echo "grep -l $apptitle /tmp/audiobooks/*AB.yaml | head -1"
the_file=$(grep -l $apptitle /tmp/audiobooks/*AB.yaml | head -1)
echo "the_file=$the_file"
if [ -z $the_file ]
then
echo "No hiera file found for $apptitle ... skipping"
continue
fi
appname=`basename $the_file .yaml`
echo "url is[$url] and apptitle is [$apptitle] appname is [$appname]"
exit 0
done
IFS=$SAVEIFS
脚本生成的输出如下:
pair http://www.example.com/product/B06XK9FGYD='A Soldier Of The Legion'
grep -l 'A Soldier Of The Legion' /tmp/audiobooks/*AB.yaml | head -1
the_file=
No hiera file found for 'A Soldier Of The Legion' ... skipping
pair http://www.example.com/product/B01GWQI0OS='Art of War Sun Tzu'
grep -l 'Art of War Sun Tzu' /tmp/audiobooks/*AB.yaml | head -1
the_file=
No hiera file found for 'Art of War Sun Tzu' ... skipping
pair http://www.example.com/product/B0717333MM='Bartleby, the Scrivener (version 2)'
grep -l 'Bartleby, the Scrivener (version 2)' /tmp/audiobooks/*AB.yaml | head -1
the_file=/tmp/audiobooks/BartlebyTheScrivener_AMZAD_AB.yaml
url is[http://www.example.com/product/B0717333MM] and apptitle is ['Bartleby, the Scrivener (version 2)'] appname is [BartlebyTheScrivener_AMZAD_AB]
奇怪的是,当我从命令行运行grep命令时,我回显的每个grep命令都能正常工作。。。例如:
$ grep -l 'A Soldier Of The Legion' /tmp/audiobooks/*AB.yaml | head -1
/tmp/audiobooks/A_Soldier_of_the_Legion_AB.yaml
脚本也适用于标题
'Bartleby, the Scrivener (version 2)'
。 最佳答案
如果这行:
echo "grep -l $apptitle /tmp/audiobooks/*AB.yaml | head -1"
产生如下输出:
grep -l 'A Soldier Of The Legion' /tmp/audiobooks/*AB.yaml | head -1
这意味着
apptitle
的值包含单引号。你可以试着了解发生了什么:
value1='A Soldier Of The Legion'
value2="'A Soldier Of The Legion'"
echo "$value1"
echo "$value2"
输出:
A Soldier Of The Legion
'A Soldier Of The Legion'
换句话说,脚本真正执行的是:
grep -l "'A Soldier Of The Legion'" /tmp/audiobooks/*AB.yaml | head -1
只有当
yaml
文件包含由单引号包围的标题时,才匹配。您可能想去掉
apptitle
中的单引号,例如:apptitle=$(echo $i | cut -d= -f2- | cut -c1-52 | sed -e "s/^'//" -e "s/'$//")
上面的
sed
将去掉每端的单引号,并将其他单引号单独留在字符串的中间。关于bash - 我的脚本中的grep命令返回空结果,但可从命令行运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44867115/