2017-02-11 147 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

问题解决了。非常感谢=] –