Home > Enterprise >  Bash script to modify an array of paths /a/b/c to just array of paths of c/
Bash script to modify an array of paths /a/b/c to just array of paths of c/

Time:01-22

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/

Thank you for any assistances!

CodePudding user response:

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

array=( "${array[@]#"$basepath"}" )

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related