Saturday, February 5, 2022

[SOLVED] I am trying to remove all info between the two brackets on the Spoken line into a separate file

Issue

I have a file.txt that contains some values. I am not sure how to extract the info from and between the brackets on a certain line.

The line is Oscar and the info I need to extract is between the brackets

Sonia = 0
Oscar = [191, 229, 115, 105, 0, 78, 154, 122, 210, 0]
EnableDebugConsole = true
Ralph = 99
Run = 0

It would be grand if I could save the value with and without the brackets so I know in the future. From this website, I gathered some examples and have tried them.

grep Oscar file.txt > file_remove.txt
cut -d \= -f 2 file_remove.txt | tr -d " \t\n\r" > file_brackets.txt
cat file_brackets.txt

[191,229,115,105,0,78,154,122,210,0]

Even thou it is probably not the nicest way to do it, I still achieved 1 of my goals and I have the info

Now how do I remove the brackets so I can have file_no_brackets.txt that holds just the values between the brackets like so

191,229,115,105,0,78,154,122,210,0

Solution

You can do it quite simply with sed, e.g.

$ sed -n '/^Oscar/s/^[^[]*[[]\([^]]*\).*$/\1/p' file
191, 229, 115, 105, 0, 78, 154, 122, 210, 0

explanation

  1. sed -n suppress printing of pattern space

  2. /^Oscar/ locate line beginning with Oscar

  3. 's/match/replace/ standard sed substitution where you match the regex match and replace it with replace

  4. Inside the substitution you have /^[^[]* match all chars not a '['

  5. [[] match the '['

  6. \([^]]*\) capture all chars not a ']' (remaining chars are matched with .*$)

  7. replace is \1 which is a back reference that replaces with the text in the capture group in 6 above.

  8. /p print the result of the match of /^Oscar/ and the substitution.

done.



Answered By - David C. Rankin
Answer Checked By - Robin (WPSolving Admin)