1

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?

mattman88
  • 475
  • 1
  • 8
  • 22
  • 2
    Possible duplicate of [How to change values of bash array elements without loop](http://stackoverflow.com/questions/12744031/how-to-change-values-of-bash-array-elements-without-loop) – Wrikken Feb 21 '17 at 00:49

3 Answers3

1

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
chepner
  • 497,756
  • 71
  • 530
  • 681
1

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.

George Vasiliou
  • 6,130
  • 2
  • 20
  • 27
0

You can still use basic string manipulation there:

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

Or, to assign it to the array:

array=(${array[@]##*/})
Wrikken
  • 69,272
  • 8
  • 97
  • 136