0

I'm fairly new to working with arrays in bash scripting. Basically I have an array created, for example:

array=( /home/usr/apple/ /home/usr/pineapple/ /home/usr/orange/ )

I want to modify this array so that the resulted modified array will look like:

array=( apple/ pineapple/ orange/ )

I tried with this block of code:

basepath=/home/usr/

# modify each item in array to remove leading /home/usr
for i in "${array[@]}"
do
  array[$i]=${i#$basepath}
done

# print all elements from array
for i in ${array[@]}
do
  printf "%s\n" "$i"
done

This gave me an syntax error: operand expected (error token is /home/usr/apple)

Expected result is it will print out the new modified array of just apple/, pineapple/ and orange/

0

3 Answers 3

6

you can strip the basepath while expanding the array and create (or update) a new array:

array=( "${array[@]#"$basepath"}" )
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to iterate and at the same time modify the contents of an array, you have to expand it by its indices:

for i in "${!array[@]}"; do
  array[i]=${array[i]#$basepath}
done

Comments

1

All without a single shell loop:

#!/usr/bin/env bash

basepath=/home/usr/

array=(/home/usr/apple/ /home/usr/pineapple/ /home/usr/orange/)

# This erases basepath prefix from each entry of array and stores back into array
array=("${array[@]#"$basepath"}")

# Prints all array entries
printf "%s\n" "${array[@]}"

EDIT: Fixed as per Farvadona's comment

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.