2014-02-05 43 views
1

我需要幫助,將grep命令的輸出設置爲每行的變量。在Bash中設置一個While循環的變量

while read line; do 
     grep -oP '@\K[^ ]*' <<< $line 
    done < tweets 

上面顯示什麼,我想是這樣的:

lunaluvbad

Mags_GB

等等......

但是,如果我會做類似:

while read line; do 
     usrs="grep -oP '@\K[^ ]*' <<< $line" 
    done < tweets 

    echo $usrs 

它顯示奇怪的結果,當然不是我正在尋找的結果。我需要$ usrs來顯示上面提到的內容。例如:

lunaluvbad

Mags_GB

+0

請仔細閱讀http://stackoverflow.com/help/someone-answers並給予信貸那些誰回答您的問題。 –

回答

2

根本不需要循環。 grep將循環輸入的反正線:

usrs=$(grep -oP '@\K[^ ]*' tweets) 
+0

這幾乎顯示我想要的,但輸出不顯示在自己的行。每個單詞都需要在自己的路線上。有什麼想法? – RydallCooper

+1

@RydallCooper打印變量時使用引號:'echo「$ usrs」' – tom

+1

@RydallCooper:如果你只是想輸出,'grep -oP'@ \ K [^] *'tweets'就是你所需要的。如果您想對輸出進行進一步處理,請告訴我們您要做什麼。 –

2

製作使用bash陣列和command substitution這樣的:

users=() 
while read -r line; do 
    users+=("$(grep -oP '@\K[^ ]*' <<< "$line")") 
done < tweets 

或者使用process substitution

users=() 
while read -r line; do 
    users+=("$line") 
done < <(grep -oP '@\K[^ ]*' tweets) 

printf "%s\n" "${users[@]}"