I have a string called "desktops" that look like this:

desktops="1 2 %{F#990000}3%{F-} 4 5 6 7 8 9 0"

The 6 digits after the "#" represent an RGB color, so the 3rd desktop have a dark red color. One of the above numbers separated between spaces can represent a focused desktop, for example:


In that case I need and output like this:

"1 2 %{F#990000}3%{F-} 4 5 6 7 8 %{F#FFFF00}9%{F-} 0"

The problem arises when the numbers in the RGB color codes are also present in the desktops list.

I tried this:

echo $desktops | sed "s/$focused/%{F#FFFF00}$focused%{F-}/"

but of course it doesn't work when the color codes have numbers present in the focused variable.

Any hints?


1 Answer 1


Match on the surrounding spaces. Temporarily add bounding spaces so you can match the first or last desktop digit in the sequence, and remove them afterwards.

echo " $desktops " | sed -e "s/ $focused / %{F#FFFF00}$focused%{F-} /" -e 's/^ \(.*\) $/\1/'

With GNU extensions or similar you can match directly on the word boundary:

    echo "$desktops" | sed -e "s/\<$focused\>/%{F#FFFF00}$focused%{F-}/"
  • It's up to POSIX to define a suitable word boundary sequence. Either solution proposed here should work, though, if you've a GNU system
    – roaima
    May 2, 2022 at 14:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .