Reputation: 495
I have a bash array with 3 elements and I need to remove the first X number characters from all the elements and the last Y number of characters from all the elements. How can this be achieved. Example below:
echo ${array[@]}
random/path/file1.txt random/path/file2.txt random/path/file3.txt
I would like this array to become
echo ${array[@]}
file1 file2 file3
How can this be achieved?
Upvotes: 1
Views: 2604
Reputation: 6345
This will go with one shot:
$ a=( "/path/to/file1.txt" "path/to/file2.txt" )
$ basename -a "${a[@]%.*}"
file1
file2
Offcourse, can be enclosed in $( ) in order to be assigned to a variable.
Upvotes: 1
Reputation: 531205
There's no way to do this in just one step; you can, however, remove the prefixes first, then the suffixes.
array=( "${array[@]##*/" ) # Remove the longest prefix matching */ from each element
array=( "${array[@]%.*}" ) # Remove the shortest suffix match .* from each element
Upvotes: 1
Reputation: 70490
You can still use basic string manipulation there:
echo ${array[@]##*/}
Or, to assign it to the array:
array=(${array[@]##*/})
Upvotes: 1