sed replace braces with brackets keeping content inside

Took me a minute to figure this out but it works.

Given the following string, I want to replace { and } with [ and ] keeping each number inside and only with a number inside the braces without space and without letters.

data.txt:

{1}: Today is tomorrow’s yesterday. {2}: This year is next year’s yesteryear. {3}: Foo {10}: Bar {100}: Baz {91919}: Qux {99119a9}: 42

sed -e ’s/{\([0-9]\+\)}/[\1]/ data.txt

rjk@debian:~$ sed -e ’s/{\([0-9]\+\)}/[\1]/’ data.txt [1]: Today is tomorrow’s yesterday. [2]: This year is next year’s yesteryear. [3]: Foo [10]: Bar [100]: Baz [91919]: Qux {99119a9}: 42 {1 2 3 4 5}: infinity and beyond.

If I want to replace anything in the braces, then I could alter the command slightly.

sed -e ’s/{\(.*\)}/[\1]/ data.txt

rjk@debian:~$ sed -e ’s/{\(.*\)}/[\1]/’ data.txt [1]: Today is tomorrow’s yesterday. [2]: This year is next year’s yesteryear. [3]: Foo [10]: Bar [100]: Baz [91919]: Qux [99119a9]: 42 [1 2 3 4 5]: infinity and beyond.

Published At