2014-10-16 30 views
1

我有一個腳本,它檢查一個文件中的一個文件中的某個文件中的一個關鍵字,看它是否存在於這兩個文件中。但是,在腳本中,grep從不返回任何已找到的內容,但是在命令行上它已完成。grep裏面的bash腳本沒有找到項目

#!/bin/bash 
# First arg is the csv file of repo keys separated by line and in 
# this manner 'customername,REPOKEY' 
# Second arg is the log file to search through 

log_file=$2 
csv_file=$1 
while read line; 
do 
    customer=`echo "$line" | cut -d ',' -f 1` 
    repo_key=`echo "$line" | cut -d ',' -f 2` 
    if [ `grep "$repo_key" $log_file` ]; then 
     echo "1" 
    else 
     echo "0" 
    fi 
done < $csv_file 

CSV文件的格式如下:

customername,REPOKEY

和日誌文件如下:

REPOKEY

REPOKEY

REPOKEY

我做./script csvfile.csv logfile.txt

回答

2

而隨後的grep命令使用grep -q檢查輸出,以檢查它的返回狀態調用腳本:

if grep -q "$repo_key" "$log_file"; then 
    echo "1" 
else 
    echo "0" 
fi 

而且你的腳本可以簡化爲:

log_file=$2 
csv_file=$1 
while IFS=, read -r customer repo_key; do 
    if grep -q "$repo_key" "$log_file"; then 
     echo "1" 
    else 
     echo "0" 
    fi 
done < "$csv_file" 
+0

嗯,改變這仍然沒有改變我原來的結果,這就像'grep'不在腳本內工作? – Rob 2014-10-16 16:20:19

+0

在'grep'插入'echo'[$ repo_key]''之前,告訴我你的值是多少 – anubhava 2014-10-16 16:22:51

0

使用的退出狀態命令打印10

repo_key=`echo "$line" | cut -d ',' -f 2` 

grep -q "$repo_key" $log_file 

if [ $? -eq 1 ]; then 
     echo "1" 
    else 
     echo "0" 
    fi 

-q supresses輸出,使得不輸出打印

$?grep上全成匹配於unsuccessfull

可以命令10的退出狀態有一個更簡單的版本,因爲

grep -q "$repo_key" $log_file 
echo $? 

這將產生相同的輸出