I'm trying to modify a file named test.txt, which contains a line like this:
```
gobbledygook
something unique I can key on ['test1', 'test2', 'test3'];
gobbledygook
```
In my script, I have:
```
substitute_string="'test1', 'test2'"
sed -E "s/something unique I can key on[(.*)];/${substitute_string}/g" test2.txt
```
However, the output in test2.txt ends up looking incorrect:
```
gobbledygook
'test1', 'test2'
gobbledygook
```
When I tried using 1 in front of the variable, I get something like:
```
gobbledygook
'test1', 'test2', 'test3''test1', 'test2'
gobbledygook
```
I'm unsure how to replace just what's inside the brackets with my substitute_string. Any suggestions?
3 Answers
You can simplify it a bit! Just use:
```
sed "s/[[^]]*]/[${substitute_string}]/g"
```
This should directly replace whatever's inside the square brackets with your substitute_string without affecting other text. Remember that you don’t need to pass the file in through stdin; sed can read it directly.
To fix your issue, you want to capture the part before and after the brackets so you can swap out the content inside them without losing the rest. Try this:
```
sed -E "s/(.*something unique I can key on[)(.*)(];.*)/1${substitute_string}3/g" test.txt > test2.txt
```
This will keep the surrounding text and only replace what's inside the brackets with your substitute strings.
Hey, to make it cleaner and less confusing, just use sed like this:
```
sed -i "s/[[^]]*]/[${substitute_string}]/g" test.txt
```
This version will replace the content directly in the file, and you don’t have to handle the output file separately. Good luck with your script!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically