-1

My question is a both a refinement and a continuation of What's the regular expression that matches a square bracket?.

I am trying to create a regex for use within sed (GNU sed) 4.4 that will replace all digits surrounded by square brackets with a new line.

The sample text is generated by dumping a bash array to a file ("sentences.tmp"), yielding:

declare -a aRecs=([0]="" [1]="some text" [10]="some more text" [100]="three-digit text")

The diesired output is:

declare -a aRecs=(
"" 
"some text" 
"some more text" 
"three-digit text")

Originally, I tried the following regex:

\[\d*\]\=

...but both M. Nejat Aydin and dan said not to use /d in sed. Thank you for that instruction.

The following regex (per M. Nejat Aydin) does give the desired hightlight text match in xed 2.0.2:

\[[0-9]+]

enter image description here

However, when I run:

sed -i 's/\[[0-9]+]/\n/g' "sentences.tmp"

--or --

sed -i 's/\[[0-9]+\]\=/\n/g' "sentences.tmp"

There is no change within "sentences.tmp" upon file re-loead.

I experimented with various other forms (including replacing with 'xxx' in lieu of '\n' or '\n' or '\\n' with the same result.

My apologies for failing to provide a sample output. I have amended the question to include the guidnace thus far. Thank you.

shamelesshacker
  • 185
  • 1
  • 7
  • 18

1 Answers1

1

Using sed

$ sed -i.bak 's/\[[^]]*]=/\n/g' input_file
declare -a aRecs=(
""
"some text"
"some more text"
"three-digit text")
HatLess
  • 10,622
  • 5
  • 14
  • 32
  • 1
    Thank you HatLess! Using your regex I was able to find an approximate explanation at https://stackoverflow.com/questions/10646418/how-to-replace-paired-square-brackets-with-other-syntax-with-sed There are a lot of pointers to things I should read there. Thank you. – shamelesshacker Jul 15 '22 at 20:56