2012-10-07 38 views
1

如果您執行的grep命令有多行,並且每行有多個字,則輸出似乎按字而不是按行存儲在數組中。你如何改變它以便每行存儲它?爲每個數組元素存儲一行grep輸出

例如:

first_title=($(egrep -o 'class\=\"title\" title\=\"'.\{1,80\} index.html 
| egrep -o title\=\".*\"\> | sed 's/title\=\"//g' | sed 's/">//g')) 


echo ${first_title[0]} 

如果回到10日線,與第一讀「這是一個行」這隻會輸出「這個」

+0

你在shell腳本在說什麼? –

+0

@VaughnCato,是的,對不起。例如:bash腳本中的an_array =('grep blah file.txt')通過在每個元素中放置一個單詞而不是整行來存儲輸出。 – Sam

+0

你可以給一些代碼來證明你的意思嗎? –

回答

2

您可以使用IFS來改變字段分隔符:

IFS=' 
' 
first_title=($(egrep -o 'class\=\"title\" title\=\"'.\{1,80\} index.html 
| egrep -o title\=\".*\"\> | sed 's/title\=\"//g' | sed 's/">//g')) 


echo ${first_title[0]} 
unset IFS 
0

如果你想添加

一個帶空格的元素,那麼你需要引用它,如下面的例子:

arr=("this is a line" "this is another line" this is some words) 
echo "${arr[0]}" 
this is a line 
printf '%s\n' "${arr[@]}" 
this is a line 
this is another line 
this 
is 
some 
words 

所以在y我們的情況下,嘗試類似的東西:

first_title=(
    $(
     egrep -o 'class\=\"title\" title\=\"'.\{1,80\} index.html | 
      egrep -o title\=\".*\"\> | 
      sed 's/title\=\"//g; 
       s/">//g; 
       s/.*/"&"/' 
    ) 
) 


echo "${first_title[0]}" 
相關問題