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/

Braiam
  • 1
  • 11
  • 47
  • 78
Christina Do
  • 11
  • 1
  • 1

3 Answers3

6

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

array=( "${array[@]#"$basepath"}" )
Fravadona
  • 13,917
  • 1
  • 23
  • 35
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
konsolebox
  • 72,135
  • 12
  • 99
  • 105
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

Léa Gris
  • 17,497
  • 4
  • 32
  • 41