You seem a bit confused about how sed works, so I'll go step by step. My
'answer' is this:
s="col(3,B,14)"; echo $s | sed 's/\(col([0-9],[A-Z],\)/\1t/g'
Explanation
There are a couple of problems here. First, you need a semi colon after
defining your variable 's', before echoing it.
s="col(3,B,14)"; echo $s
Next, sed substitution works by 's/pattern/replacement/' - where 'pattern' is a
regular expression, but where 'replacement' is not. That is, putting something
like '[0-9]' in the replacement will not represent any digit, but instead
represent the five characters: [
, 0
, -
, 9
, and ]
. Also, the /g
at
the end means to keep applying the substitution on a string for every match of
the pattern (so if you had a line like echo hello world | sed 's/o/z/g'
then
the output would be 'hellz wzrld'. Whereas echo hello world | sed 's/o/z/'
would give 'hellz world')
So let's remove your replacement for now:
s="col(3,B,14)"; echo $s | sed 's/col([0-9],[A-Z],[0-9])/replacement/g'
Turning attention to the regular expression pattern you used, it says match a
string like 'col(<single digit>,<uppercase letter>,<single digit>)' - notice
that the last [0-9]
piece won't match '14', since that is two digits and so
your pattern would match say 'col(3,B,1)' but will not match 'col(3,B14)'. To
match one or more digits, you can use [0-9][0-9]*
:
To do the replacement as you want, the best way would be to use a 'capture
group'. Capture groups 'remember' part of the match for later use. You put \(
and \)
around the part of the pattern you want to remember and use \1
to
refer to it later:
s="col(3,B,14)"; echo $s | sed 's/\(col([0-9],[A-Z],\)/\1replacement/g'
This will match 'col(<single digit>,<uppercase letter>,' - so up to and
including the point where you want to add a 't'. All of this matched stuff will
be put back in the replacement (\1
) followed by any text you add (in this
case we're adding the literal text 'replacement'). Any remaining text not
matched in the input will be unaffected. The above will output:
col(3,B,1replacement4)
So if we now put a 't' in the replacement string:
s="col(3,B,14)"; echo $s | sed 's/\(col([0-9],[A-Z],\)/\1t/g'
We get:
col(3,B,t14)
If you want to learn sed well, I can recommend an excellent tutorial.