Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array elements in sed operation

Tags:

bash

sed

I am trying to replace elements on an array using a sed command to compare values between two arrays and replace them accordingly, with the following terminal input:

#!/bin/bash

icons=("" "󰈹" "" "" "") #NerdFont icons
classes=("kitty" "firefox" "discord" "steam" "inkscape")

windowClasses=(kitty kitty kitty kitty steam firefox kitty)

echo $(echo $windowClasses | sed "s/${classes[@]}/${icons[@]}/g")

This, however, outputs the following error:

sed: -e expression #1, char 7: unterminated `s' command

I noticed that if I replace the @ symbol for a number as the array selector the code works as expected, but only replaces the elements in the array with the respective elements in the other arrays (kitty becomes  but firefox doesn't change, for instance) .

like image 780
Caio Avatar asked Jun 24 '26 22:06

Caio


1 Answers

This doesn't use sed but associative arrays instead:

declare -A classes
classes["kitty"]=""
classes["firefox"]="󰈹"
classes["discord"]=""
classes["steam"]=""
classes["inkscape"]=""
windowClasses=("kitty" "kitty" "kitty" "kitty" "steam" "firefox" "kitty")
for KEY in "${windowClasses[@]}"
do
   echo ${classes[$KEY]}
done
like image 103
Eduardo Avatar answered Jun 28 '26 00:06

Eduardo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!