How can I correctly substitute a string within brackets in a file using sed?

0
13
Asked By CuriousCoder42 On

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

Answered By CodeWizard88 On

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.

Answered By HelpfulHannah93 On

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.

Answered By SyntaxSleuth On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.