Skip to content
Advertisement

Get words from positions in string – Bash/Linux

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.

JavaScript

The id’s in the string is freepbx and cidlookup, the names are NEWUPDATES and noauth.

I’d like them to come out like:

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement