First of all, you have to ensure that your key
variable does not contain any characters with special meaning for your sed
command, like for example /
which is the default separating character for the sed substitution. In such a case you could use a different character, for example like this "s@pattern@replacement@g" file
.
Then you need to match from an opening until the corresponding closing bracket. That would be \[.*\]
but sed is greedy: In case your line contains [text1] text2 [text3]
, sed will match all of this. So you need to define, instead of .*
, any character which is not a closing bracket, zero or more times: [^]]*
.
Note that in the above, we don't need to escape (\]
) the bracket in the middle, because sed
awaits for at least one character to exclude after the caret (^
), so it will not misread this as the closing bracket of the list of the excluded characters, but as a literal bracket.
Now if you want to make the change in-place, you can use -i
like described in this post. But first test without -i
, check a part of the output to see if it looks good.
So this sed
is expected to work for your case:
sed -i "s/\[[^]]*\]/$key/g" file
\[[^]]*\]
. This is a regular expression, to be used in sed. If you had a star alone instead of[^]]*
it would be a shell glob expression (matching anything). – thanasisp Nov 01 '20 at 20:25