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
sed -n
suppress printing of pattern space/^Oscar/
locate line beginning withOscar
's/match/replace/
standardsed
substitution where you match the regexmatch
and replace it withreplace
Inside the substitution you have
/^[^[]*
match all chars not a'['
[[]
match the'['
\([^]]*\)
capture all chars not a']'
(remaining chars are matched with.*$
)replace
is\1
which is a back reference that replaces with the text in the capture group in6
above./p
print the result of the match of/^Oscar/
and the substitution.
done.
Answered By - David C. Rankin Answer Checked By - Robin (WPSolving Admin)