Reputation: 5454
Any idea how a can take a string like:
string=1,2,3,4,5
and using
number=4
put
<font color='red'><b></b></font>
around the corresponding number so the final product is:
newstring=1,2,3,<font color='red'><b>4</b></font>,5
Thanks for the help
Upvotes: 2
Views: 267
Reputation: 63962
Pure bash?
string="1,2,3,4,5"
num=4
re="(^|.+,)($num)(,.+|$)"
if [[ "$string" =~ $re ]]
then
echo -n "${BASH_REMATCH[1]}"
echo -n "<font>${BASH_REMATCH[2]}</font>"
echo "${BASH_REMATCH[3]}"
else
echo "$num doesn't match"
fi
will produce:
1,2,3,<font>4</font>,5
or perl:
echo '1,2,3,4,5' | num=4 perl -F, -lapE '$_=join ",",map{/\b$ENV{num}\b/? "<font>$_</font>":$_}@F'
Upvotes: 0
Reputation:
echo "$string" | sed "s#\(,\|^\)\($number\)\(,\|\$\)#\\1<font color='red'><b>\\2</b></font>\\3#g"
Should work good enough in most cases.
Upvotes: 0
Reputation: 545923
You can use sed
:
result="$(sed "s|\($number\)|<font color='red'><b>\1</b></font>|" <<< "$string")"
The general form is: sed s|search pattern|replace|
where |
is some unique delimiter (normally you’d use /
but that is already used in your string for other purposes). \(…\)
is a capture group which captures the hit – in this case 4
and which can be used in the replace string via \1
.
Upvotes: 1