我有一個腳本試圖在任意文本檔案中查找給定字串的存在。
我已經解決了類似的問題:
#!/bin/bash
file="myfile.txt"
for j in `cat blacklist.txt`; do
echo Searching for $j...
unset match
match=`grep -i -m1 -o "$j" $file`
if [ $match ]; then
echo "Match: $match"
fi
done
Blacklist.txt 包含潛在匹配的行,如下所示:
matchthis
"match this too"
thisisasingleword
"This is multiple words"
myfile.txt 可能類似于:
I would matchthis if I could match things with grep. I really wish I could.
When I ask it to match this too, it fails to matchthis. It should match this too - right?
如果我在 bash 提示符下運行它,如下所示:
j="match this too"
grep -i -m1 -o "$j" myfile.txt
...我也得到“匹配這個”。
但是,當批處理檔案運行時,盡管變數設定正確(通過回顯行驗證),但它永遠不會正確 grep 并且不回傳任何內容。
我哪里錯了?
uj5u.com熱心網友回復:
不會
grep -owF -f blacklist.txt myfile.txt
與其撰寫一個低效的回圈,不如做你想做的事?
uj5u.com熱心網友回復:
有了這個:
if [ $match ]; then
您正在將隨機引數傳遞給test. 這不是您正確檢查變數 net 是否為空的方式。使用test -n:
if [ -n "$match" ]; then
您也可以使用grep's 退出代碼:
if [ "$?" -eq 0 ]; then
for ... in X默認情況下在空格處拆分 X,并且您希望腳本匹配整行。
正確定義IFS:
IFS='
'
for j in `cat blacklist.txt`; do
blacklist.txt包含"match this too"帶引號,并且通過for回圈讀取并按字面意思匹配。
j="match this too"不會導致j變數包含引號。
j='"match this too"'確實如此,然后它將不匹配。
由于現在從檔案中正確讀取了整行blacklist.txt,因此您可能可以從該檔案中洗掉引號。
腳本:
#!/bin/bash
file="myfile.txt"
IFS='
'
for j in `cat blacklist.txt`; do
echo Searching for $j...
unset match
match=`grep -i -m1 -o "$j" "$file"`
if [ -n "$match" ]; then
echo "Match: $match"
fi
done
uj5u.com熱心網友回復:
請你試試:
#!/bin/bash
file="myfile.txt"
while IFS= read -r j; do
j=${j#\"}; j=${j%\"} # remove surrounding double quotes
echo "Searching for $j..."
match=$(grep -i -m1 -o "$j" "$file")
if (( $? == 0 )); then # if match
echo "Match: $match" # then print it
fi
done < blacklist.txt
輸出:
Searching for matchthis...
Match: matchthis
Searching for match this too...
Match: match this too
match this too
Searching for thisisasingleword...
Searching for This is multiple words...
uj5u.com熱心網友回復:
我最終完全放棄了 grep 并改用 sed 。
match=`sed -n "s/.*\($j\).*/\1/p" $file
效果很好,我能夠在黑名單檔案中使用未參考的多個單詞短語。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/410234.html
標籤:
