I have the following string that I want to extract name and id from and store them in a variable. This is just an example, the list can be longer but they are separated the same way.
[["freepbx","NEWUPDATES","There are 6 modules available for online upgrades"],["cidlookup","noauth","OpenCNAM Requires Authentication"]]
The id’s in the string is freepbx and cidlookup, the names are NEWUPDATES and noauth.
I’d like them to come out like:
freepbx NEWUPDATES cidlookup noauth
I’m running a program from command line that needs it’s input this way.
Any help is greatly appreciated!
Advertisement
Answer
This is one way to do it:
echo '[["freepbx","NEWUPDATES","There are 6 modules available for online upgrades"],["cidlookup","noauth","OpenCNAM Requires Authentication"]]' | sed -e 's/],[/n/g' -e 's/([[)*"//g' | awk -F ',' '{print $1, $2}' freepbx NEWUPDATES cidlookup noauth
Explanation:
The sed
command s/],[/n/g
will replace all ]
, [
which separate each record with a new line(n
) character. This will allow you to treat each line as a separate record which makes all other tools much easier:)
The second sed
command s/([[)*"//g
will remove the quotes and the initial [[
at the start of the first record. This cleans up things from your data leaving only the ,
between your fields.
Finally, awk
command -F ',' '{print $1, $2}'
, the -F
tells awk
to use the ,
as field separator (instead of space) and $1
and $2
to print the first and second fields.