2016-03-23 37 views
1

我目前正在創建一個數據庫在bash中。我想添加一個「和」功能。這個函數將搜索兩件事,並且只返回匹配兩個搜索的東西。我將如何實現這一目標?grep多個東西出故障

這裏是我的代碼:

#!/bin/bash 

clear 

#return all 
function all { 
    cat people.dat 
} 
#return some 
function search { 
    grep -i "$SEARCH" people.dat || echo "search returned nothing" 
} 
#or search 
function or { 
    egrep -i "$search1|$search2" people.dat 
} 
#and search 
function and { 
    if [[ $(grep -i "$search1") = $(grep -i "$search2") ]]; then 
     echo yes 
     #that is temporary I want to see if it worked 
    fi 
} 
#return null 
function null { 
    return 
} 

while [ true ] 
do 
    #get the search 
    read SEARCH 

    #search 
    if [[ $SEARCH == *" OR "* ]]; then 
     search1=${SEARCH%" OR "*} 
     search2=${SEARCH##*" OR "} 
     or 
    elif [[ $SEARCH == *" AND "* ]]; then 
     search1=${SEARCH%" AND "*} 
     search2=${SEARCH##*" AND "} 
     and 
    elif [ "$SEARCH" = "all" }; then 
     all 
    elif [ "$SEARCH" = "exit" ]; then 
     exit 
    elif [ "$SEARCH" = "" ]; then 
     null 
    else 
     search 
    fi 
done 
+0

這是功課?我真的希望你不打算在Bash中實現生產數據庫... – l0b0

+0

你可以像這樣使用sed:'sed -n「/ $ a/{/ $ b/p}」'用於AND和'sed - n「/ $ a \ | $ b/p」'爲OR – andlrc

+0

搜索字符串是否可以重疊?例如:'search1 =「a b」''search2 =「b c」'string =「a b c」。這裏'grep「$ {search1}。* $ {search2}」<<<「$ {string}」'將會失敗。 –

回答

0

管的第一grep輸出輸入到第二grep。只有$search1$search2的行纔會被退回。

function and { 
    if [[ $(grep -i "$search1" people.dat | grep -i "$search2") ]]; then 
     echo yes 
    fi 
} 
+0

謝謝,這確實有幫助。 :) – Luke

0

@munircontractor is on the right track。你可以做到這一點更簡單:

function and { 
    if grep -i "$search1" people.dat | grep -qi "$search2"; then 
     echo yes 
    fi 
} 

如果沒有匹配的第一個grep的輸出將是空的,則退出代碼將被忽略,而輸出將通過管道發送。第二個grep將在找到匹配時立即停止搜索,不會打印任何內容,以及是否找到某個內容將決定整個管道的退出代碼。

其他提示:

  • 您可以使用簡單的while true
  • 你可能想使用read -r,以避免治療反斜槓作爲逃避特殊字符