2017-02-21 29 views
0

我有一個包含3個元素的bash數組,我需要從所有元素中刪除第一個X數字字符,並從所有元素中刪除最後的Y個字符。這怎麼能實現。下面的例子:在Bash中刪除數組中的每個元素的開始和結束

echo ${array[@]} 
random/path/file1.txt random/path/file2.txt random/path/file3.txt 

我想這個數組成爲

echo ${array[@]} 
file1 file2 file3 

如何才能實現這一目標?

+2

可能重複的[如何更改bash數組元素的值而不使用循環](http://stackoverflow.com/questions/12744031/how-to-change-values-of-bash-array-elements-without-loop ) – Wrikken

回答

1

這將大大有一個鏡頭:

$ a=("/path/to/file1.txt" "path/to/file2.txt") 
$ basename -a "${a[@]%.*}" 
file1 
file2 

Offcourse,可以在$(),以包圍被分配給一個變量。

+0

這正是我想要的,比你! – mattman88

-1

,您仍然可以使用有基本的字符串操作:

echo ${array[@]##*/} 

或者,將其分配到數組:

array=(${array[@]##*/}) 
+0

這只是問題提問的一半。 – chepner

+0

啊檢查,嗯,我只是添加了作爲佔位符,直到我們有足夠的重複投票;) – Wrikken

0

有沒有辦法,只需一個步驟做到這一點;但是,您可以先刪除前綴,然後刪除後綴。

array=("${array[@]##*/") # Remove the longest prefix matching */ from each element 
array=("${array[@]%.*}") # Remove the shortest suffix match .* from each element 
相關問題