2013-03-28 66 views
8

这是我如何创建我的bash数组:如何在BASH中从数组中提取特定元素?

while read line 
do 
    myarr[$index]=$line 
    index=$(($index+1)) 
done < lines.txt 

文件“lines.txt”下列字符串constists

hello big world! 
how are you 
where am I 

创造${myarr[@]}后,我可以轻松地访问每一个元素(行)在这个阵列发行

echo ${myarr[2]} 

但是,如果我只想提取world!?是否可以从myarr的0元素中提取world!?什么是最重要的,是否有可能从myarr元素中提取任何最后一个单词?

我知道,在Python中,你可以做myarr[0][3]和会做的伎俩,怎么样的bash?

+0

数组元素是字符串 - 行的副本。他们本身并不是单词或任何东西的阵列。如果您愿意,可以将数组元素分开,但不会自动将数组元素拆分为单词。 –

+0

是啊,这是有道理的 – minerals

回答

6

这是使用改性剂在变量扩展许多方式

set ${myarr[2]} 
echo $3 
+1

推荐:'设置 - $ {mayarr [2]}'这样,如果在数组元素的值是'-x -e',你的shell不启动跟踪和错误退出。 –

+5

'a =($ {myarr [2]}); echo $ {a [3]}'是等价的,并且不会覆盖您可能用于其他事情的shell /函数位置参数。 – chepner

5

可以从字符串中提取字(这是数组元素是)之一:#(删除前缀),##(删除前缀,贪婪),%(删除后缀)和%%(删除后缀,贪婪)。

$ myarr=('hello big world!' 'how are you' 'where am I') 
$ echo "${myarr[0]}"  # Entire first element of the array 
hello big world! 
$ echo "${myarr[0]##* }" # To get the last word, remove prefix through the last space 
world! 
$ echo "${myarr[0]%% *}" # To get the first word, remove suffix starting with the first space 
hello 
$ tmp="${myarr[0]#* }" # The second word is harder; first remove through the first space... 
$ echo "${tmp%% *}"  # ...then get the first word of what remains 
big 
$ tmp="${myarr[0]#* * }" # The third word (which might not be the last)? remove through the second space... 
$ echo "${tmp%% *}"  # ...then the first word again 
world! 

正如你所看到的,你可以得到相当看中这里,而是把它变成一个数组的某一点@ chepner的建议变得容易得多。另外,我建议提取第二等字的公式是有点脆弱:如果你用我的公式来提取只有两个词串的第三个词,第一调整会失败,而且会风打印第一个(!)单词而不是空白。另外,如果你在一排有两个空格,这将把它作为与在它两侧的空间零长度字...

BTW,构建阵列时,我认为这是一个有点清洁剂使用+=(newelement)而不是明确地跟踪数组索引:

myarr=() 
while read line, do 
    myarr+=("$line") 
done < lines.txt