Kamal Singhal
Kamal Singhal

Reputation: 5

how to extract key value from bash string

I am trying to extract the value of a, b and c from the given bash string:

x='a: 7  b: 2  c: 7'

But I am not able to find a simpler way yet, tried to convert the string to array, but that works on the assumption that a, b and c are in sequence.

Upvotes: 0

Views: 1009

Answers (2)

knittl
knittl

Reputation: 265201

Does the key always come before a colon and comprises only non-blank characters? If so, what prevents you from running grep with the --only-matching option? Clean up the output with cut (or tr -d or sed)

echo "$x" | grep -o '[^ ]*:' | cut -d: -f1

Or, if you want the values (not the keys) – which is not clear from the question – you could split on the double-space (assuming the format is always exactly like that).

echo "$x" | sed 's/  /\n/g' | cut -d: -f2- | cut -c2-

Upvotes: 1

choroba
choroba

Reputation: 241848

You can use parameter expansion.

#!/bin/bash

x='a: 7  b: 2  c: 7'
x=" $x"
for key in a b c ; do
    value=${x#* $key: }  # Remove everything before " k: " where k is the key
    value=${value%% *}   # Remove everything after the first space
    echo Value of "$key" is "$value"
done

Upvotes: 0

Related Questions