0

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.

4
  • 1
    What have you tried? "not able to find a simpler way" … simpler than what exactly? Commented May 6, 2021 at 16:48
  • 1
    Please add your desired output (no description, no images, no links) for that sample input to your question (no comment). Commented May 6, 2021 at 16:58
  • Sorry for not adding what i tried , i tried below: array_x=($x) a="${array_x[1]}" b="${array_x[3]}" c="${array_x[5]}" Commented May 6, 2021 at 17:16
  • I need to extract keys as 3 more bash variable and assign the given value to them so it becomes a=7; b=2 and c=7 Commented May 6, 2021 at 17:31

2 Answers 2

1

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-
Sign up to request clarification or add additional context in comments.

1 Comment

I need to extract keys as 3 more bash variable and assign the given value to them
0

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

3 Comments

this breaks if i change the sequence of a, b and c. x='a: 7 c: 2 b: 7' , I dont know what sequence it would be. but yes those keys will exists in the string
@KamalSinghal: What do you mean by "breaks"? I'm still getting the correct values. Do you mean you want to get the keys in the same order, too?
No, my bad... i again rechecked it and getting the right value, so This works as expected. Thank you!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.