Hi all,
is there anyone good at bash who will help me?
I need to use syntax ${string/pattern/replacement}
The problematic part where I am stuck is:
#!bin/bash
text="A cat is on a mat."
exp="cat"
newexp="SOMECODEcatSOMECODE"
newtext=${${text}/${exp}/${newexp}}
== > ERROR "wrong substitution"
newtext=${$text/$exp/$newexp}
== > ERROR "wrong substitution"
newtext=${"cat is here"/"cat"/"dog"}
== > newtext is EMPTY STRING - Why not "dog is here" ?
Any ideas what i am doing wrong? Or would you approach it differently?
Thanks for your help.
As for the use, I am to create a bash file colorscript.sh that
1) Gets pairs color-regex, such as: r 'bar[a-z]*\>' g 'text' b 'reg'
2) Reads user's input and colors each input line properly.
Works on Solaris via PuTTY emulating a vt100 terminal:
$ cat x
#!/bin/bash
# Define terminal escape sequences.
GREEN="\033[1;32m" # bold, green
NORM="\033[0m"
text="A cat is on a cat mat." # Added a second "cat"
exp="cat"
# 1 slash matches the first occurance, 2 matches all occurances.
newtext=${text//$exp/$GREEN$exp$NORM}
echo -e "$newtext"
exit 0
$ ./x
A cat is on a cat mat.
$
Actually, this is closer to your original request:
#!/bin/bash
GREEN="\033[1;32m"
NORM="\033[0m"
text="A cat is on a cat mat."
exp="cat"
newexp="${GREEN}${exp}${NORM}"
newtext=${text//$exp/$newexp}
echo -e "$newtext"
exit 0
Thanks a lot! The documentation pretty much sucks when it says ${string/pattern/replacement} , but only pattern and replacement can have dollar signs even though all three are variables :wall:
Actually the leading dollar sign in ${string/pattern/replacement} tells the shell to perform the search/replace on $string (in this example $text).
In other words, $string is the variable the search/replace will operate on. That's why you surround it in curly braces.