2017-02-11 140 views
0

我需要編寫一個足球聯賽表足球輪投票結果在這種格式的文本文件分割字符串轉換成字符串和整數慶典

abc 4 def 5 ghi 9 hef 10 

其中format是

[home team][home team points][guest team][guest team points] 

而且程序將接受五個團隊並有多個文本文件可供閱讀。我不知道的是如何獲得每個相應團隊的積分。我已經看到一些解決方案,在這個網站中用一個空白和分隔符來解析字符串。但是,我需要像這樣讀取abc 4def 5等等。有沒有解決方法?

以下是此時的代碼。我只是想清楚如何閱讀團隊的相應分數。感謝您的幫助。

if [ $# -eq 0 ]; then 
    echo "No argument" 
else 
    echo "The number of arguments : $#" 
    echo "The full list : [email protected]" 
    myArray=("[email protected]") 
    echo "${myArray[0]}" 
    arraylength=${#myArray[@]} 
    declare -p myArray 
    #loop for places entered 
    for ((i=0;i<${arraylength};i++)); 
    do 
    #iterate on the files stored to find target 
    for matchfile in match*.txt; 
     do 
     declare file_content=$(cat "${matchfile}") 
     #check whether a file has target lanaguage 
     if [[ " $file_content " =~ ${myArray[i]} ]] # please note the space before and after the file content 
      then 
       #awk -v a="$file_content" -v b="${myArray[i]}" 'BEGIN{print index(a,b)}' 
       #echo "${myArray[i]}" 
       #let j=j+1 
     echo "${myArray[i]} found in ${matchfile}: with a score ..." 

        fi 
     done 
    done 
    fi 
exit 

回答

1

既然你已經有一個正則表達式匹配會:

if [[ " $file_content " =~ ${myArray[i]} ]]; then 

你可以像這樣進行調整:

re="(^|)${myArray[i]} ([0-9]*)(|$)" 
if [[ $file_content =~ $re ]]; then 

(^|)(|$)零件確保它正常工作,如果有空間或團隊名稱後的文件開始或結尾。 ([0-9]*)部分是將分數記錄到「捕獲組」中。

運行那個正則表達式匹配會將數組BASH_REMATCH與比較中的所有匹配組合在一起,因此${BASH_REMATCH[2]}將得分。

+0

問題解決了。非常感謝=] –