我正在撰寫腳本,該腳本將從關鍵字和單獨檔案中的其他關鍵字串列中找到模式。
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 單詞。
關于如何實作這一目標的任何幫助?
uj5u.com熱心網友回復:
建議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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/447754.html
