Se proprio non è possibile utilizzare una corretta parser JSON come jq
[1] , provare un awk
soluzione basata su:
Bash 4.x:
readarray -t values < <(awk -F\" 'NF>=3 {print $4}' myfile.json)
Bash 3 .x:
IFS=$'\n' read -d '' -ra values < <(awk -F\" 'NF>=3 {print $4}' myfile.json)
Questo negozi tutte le proprietà valori nell'array Bash ${values[@]}
, che è possibile controllare con
declare -p values
.
Queste soluzioni hanno limitazioni:
- ogni proprietà deve essere su una riga separata,
- tutti i valori devono essere a doppio citato,
- incorporati virgolette doppie escape non sono supportati.
Tutte queste limitazioni rafforzano la raccomandazione di utilizzare un parser JSON corretto.
Nota: Le seguenti soluzioni alternative usare il 4.x + readarray -t values
comando bash, ma funziona anche con l'alternativa Bash 3.x, IFS=$'\n' read -d '' -ra values
.
grep
+ cut
combinazione: un unico comando grep
non farà (a meno che non si utilizza GNU grep
- vedi sotto), ma aggiungendo cut
aiuta:
readarray -t values < <(grep '"' myfile.json | cut -d '"' -f4)
GNUgrep
: Utilizzo di -P
per supportare PCREs, quale supporto t \K
di mollare tutto abbinato finora (un più flessibile alternativa ad un look-dietro affermazione), così come asserzioni look-ahead ((?=...)
):
readarray -t values < <(grep -Po ':\s*"\K.+(?="\s*,?\s*$)' myfile.json)
Infine, ecco un puro Bash (3 .x +) soluzione:
ciò che rende questo una valida alternativa in termini di prestazioni è che non utility esterne vengono chiamati in ogni iterazione del ciclo; tuttavia, per i file di input più grandi, una soluzione basata su utility esterne sarà molto più veloce.
#!/usr/bin/env bash
declare -a values # declare the array
# Read each line and use regex parsing (with Bash's `=~` operator)
# to extract the value.
while read -r line; do
# Extract the value from between the double quotes
# and add it to the array.
[[ $line =~ :[[:blank:]]+\"(.*)\" ]] && values+=("${BASH_REMATCH[1]}")
done < myfile.json
declare -p values # print the array
[1] Ecco cosa una robusta soluzione basata su jq
sarebbe simile (Bash 4.x):
readarray -t values < <(jq -r '.[]' myfile.json)
Usa 'jq' per questo. – sjsam
Dai un'occhiata a [\ [this \]] (http://unix.stackexchange.com/questions/177843/parse-one-field-from-an-json-array-into-bash-array) domanda e mostra un po 'di sforzo da parte tua per risolvere questo. – sjsam
Questo 'cat myfile.json | nome grep | cut -d ':' -f2' potrebbe aiutare. –