我正在写一个ksh脚本。我在目录中有一对html文件,我需要检查文件是否包含两个字符串之一(字符串是互斥的)。然后,我根据它们包含的两个字符串中的哪一个重命名文件。
测试时,我可以在.txt
文件上使用以下代码,但在.html
文件中测试字符串时,该功能不再有效:
outageString='Scheduled Outage List'
jobString='Scheduled Job List'
for file in `ls -1t $fileNameFormat | head -n 2`
do
if grep -xq "$outageString" "$file"; then
mv "$file" "$outageFileName"
elif grep -xq "$jobString" "$file"; then
mv "$file" "$jobFileName"
fi
done
注意:我已独立测试了上面的ls
命令,并返回了相应的文件。
文件内容:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>
OUS: Scheduled Outage List
</title>
</head>
<body>
<h3>
OUS: Scheduled Outage List
</h3>
.
.
.
问:是否有人了解为什么grep
在搜索两个文件中的字符串时没有返回适当的值(即grep
为什么会这样做?无法识别文件中是否存在字符串)?
答案 0 :(得分:5)
问题出在您的使用中:
grep -x
由于带有grep
的{{1}}命令会尝试匹配完整的完整行。根据{{1}}:
-x
只需使用man grep
代替-x, --line-regexp
Only input lines selected against an entire fixed string or regular expression are
considered to be matching lines.
。
PS:建议不要像这样使用grep -Fq
的输出。最好直接在grep -xq
循环中使用 globbing ,如下所示:
ls
答案 1 :(得分:2)
grep中的-x选项将精确的正则表达式匹配作为整行匹配,因此HTML文档中的行开始&#34; OUS:&#34;它不会匹配。
我只能猜测.txt文件没有这个。
答案 2 :(得分:0)
试试这个:
for file in $(grep -H "Scheduled Outage List" /path/to/files/*.html | cut -d: -f1);
do
echo $file;
# mv files around
done