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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This does exactly what I wanted, than you!
1

You can still use basic string manipulation there:

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

Or, to assign it to the array:

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

2 Comments

This only does half of what the question asks.
Ah check, well, I only added is as placeholder until we have enough duplicate votes anyway ;)
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

1 Comment

It is important to double-quote ${NAME[@]}, otherwise it joins array content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.