Bash 循环输入文件并找出是否使用了行
我使用bash循环浏览一个大的输入文件(contents.txt),该文件如下所示:Bash 循环输入文件并找出是否使用了行,bash,loops,input,awk,grep,Bash,Loops,Input,Awk,Grep,我使用bash循环浏览一个大的输入文件(contents.txt),该文件如下所示: searchterm1 searchterm2 searchterm3 …试图从文件中删除未在代码库中使用的搜索词。我正在尝试使用grep和awk,但没有成功。我还想排除图像和常量目录 #/bin/bash while read a; do output=`grep -R $a ../website | grep -v ../website/images | grep -v ../website/cons
searchterm1
searchterm2
searchterm3
…试图从文件中删除未在代码库中使用的搜索词。我正在尝试使用grep和awk,但没有成功。我还想排除图像和常量目录
#/bin/bash
while read a; do
output=`grep -R $a ../website | grep -v ../website/images | grep -v ../website/constants | grep -v ../website/.git`
if [ -z "$output" ]
then echo "$a" >> notneeded.txt
else echo "$a used $($output | wc -l) times" >> needed.txt
fi
done < constants.txt
notneeded.txt
searchterm1 used 4 times
searchterm3 used 10 times
searchterm2
我也曾以类似的方式尝试过awk,但我无法让它按需要循环和输出不确定,但听起来像是在寻找类似的东西(假设文件名中没有空格):
可能有一些
find
选项使白鹭变得不必要。因此,您正在检查contents.txt
中的单词是否出现在多个文件website
、website/images
等中。出现的行应该存储在needed.txt
中,而notneeded.txt中的其他人呢?你明白了!我想递归地查找../website目录,但从搜索中排除../website/images../website/constants和../website/.git目录。搜索将通过数千个文件进行。contents.txt的输入将有大约40行我想要grep的关键术语,因此它应该循环40次。不要检查grep的输出是否为非空。相反,您可以使用grep返回的值:if grep-q。。。;然后。。。;其他的fi
find../website\(-name images-prune-o-name常量-prune-o-name.git-prune\)-o-type f
好了。我认为这是一个删节,我只是不确定,而且太懒了,无法查找语法。谢谢可能最好编写它find../website\(-name images-o-name constants-o-name.git\)-prune-o-type f
。如果我尝试原始版本,我会得到:第21行:/usr/bin/awk:参数列表太长。。。。。。。如果我将最后一行替换为:'constants.txt$(find../website(-name images-o-name constants-o-name.git)-prune-o-type f.–),那么我会得到:find:–:未知的主要或运算符awk:源代码行13的语法错误上下文是打印术语“已使用”点击[term]“times”>>>>>所需。需要时出现语法错误。
是因为我没有将文件名放在引号内,我已经更新了答案来解决这个问题。您使用的find
的哪个版本应该无关紧要,因为生成的文件名列表应该是相同的。请使用更正的脚本重试。如果你的arg列表太长,请告诉我们你的awk版本。如果您使用的是SOlaris,请不要使用/usr/bin/awk,因为它是旧的、损坏的awk-请使用/usr/xpg4/bin/awk或nawk。最佳选择-获得GNU awk。
awk '
NR==FNR{ terms[$0]; next }
{
for (term in terms) {
if ($0 ~ term) {
hits[term]++
}
}
}
END {
for (term in terms) {
if (term in hits) {
print term " used " hits[term] " times" > "needed.txt"
}
else {
print term > "notneeded.txt"
}
}
}
' constants.txt $( find ../website -type f -print | egrep -v '\.\.\/website\/(images|constants|\.git)' )