提问人:grge3113 提问时间:3/20/2022 更新时间:3/20/2022 访问量:730
Bash 循环到文件末尾
Bash Loop Through End of File
问:
我正在编写脚本,该脚本将从关键字和其他关键字列表中的单独文件中找到模式。
File1 包含列表,即每行一个单词。File2 有另一个列表 - 我真正想要搜索的列表。
while read LINE; do
grep -q $LINE file2
if [ $? -eq 0 ]; then
echo "Found $LINE in file2."
grep $LINE file2 | grep example
if [ $? -eq 0 ]; then
echo "Keeping $LINE"
else
echo "Deleting $LINE"
sed -i "/$LINE/d" file2
fi
else
echo "Did not find $LINE in file2."
fi
done < file1
我想要的是从 file1 中获取每个单词,并在 file2 中搜索它的每个实例。从这些实例中,我想搜索包含单词 example 的所有实例。任何不包含示例的实例,我想删除它们。
我的代码,它从 file1 中获取一个单词并在 file2 中搜索它的实例。找到该实例后,循环将移动到 file1 中的下一个单词,此时它应该继续搜索 file2 中的前一个单词;只有当它完成对当前单词的 file2 搜索后,它才应该移动到下一个 file1 单词。
关于如何实现这一目标的任何帮助?
答:
0赞
Dudi Boy
3/20/2022
#1
建议脚本,每个文件仅扫描一次。awk
awk 'FRN == RN {wordsArr[++wordsCount] = $0} # read file1 lines into array
FRN != RN && /example/ { # read file2 line matching regExp /example/
for (i in wordsArr) { # scan all words in array
if ($0 ~ wordsArr[i]) { # if a word matched in current line
print; # print the current line
next; # skip rest of words,read next line
}
}
}' file1 file2
评论
grep -f file1 file2
??这样就可以了。避免调用实用程序(例如 和 ,等等。在 shell 脚本的循环中。每次对实用程序的调用都会向一个单独的子 shell(进程)发送垃圾邮件,并且很快就会变得非常低效。sed
grep
grep -f file1 file2 | grep example
. 指定包含正则表达式列表的文件。添加固定字符串/无正则表达式。-f
-F