0

i have a string like

a=b c=d e=f g=h i=j j=k

How to parse this string to get the value of j?

3
  • 3
    what did you done sor far for this? Commented Sep 18, 2017 at 11:50
  • 1
    Why "j"? What's unique about it? Is there a fixed pattern? Commented Sep 18, 2017 at 11:55
  • How are you getting this string input? Commented Sep 18, 2017 at 14:00

4 Answers 4

1

This will print anything followed by j= till upcoming space regardless of column number of j.

 echo "a=b c=d e=f g=h i=j j=k" |grep -oP 'j=\K[^ ]+'
 k

If you mean, the value of last column, which in this case is j=k:

echo "a=b c=d e=f g=h i=j j=k" |awk '{split($NF,a,"=");print a[2]}'
k

Note: Solution 1 is based on regex for the value of j, whereas solution 2 is for the last column's value. Its up to you to chose which one fits better to your requirement.

Or using gensub of awk:

echo "a=b c=d e=f g=h i=j j=k" |awk '{J=gensub(/.*j=([^ ]+).*/,"\\1","g");print J}'
k

or using gawk match function:

echo "a=b c=d e=f g=h i=j j=k" |awk '{match($0,/.*j=([^ ]+).*/,a);print a[1]}'
k

or using sed back refrencing:

echo "a=b c=d e=f g=h i=j j=k"|sed -r 's/.*j=([^ ]+).*/\1/'
k
Sign up to request clarification or add additional context in comments.

Comments

0

With awk:

awk '{ for (i=1;i<=NF;i++) { split($i,arr,"=");if (arr[1]=="j") { print arr[2] } } }' <<< "a=b c=d e=f g=h i=j j=k"

Look through each space separated field and then further split the fields into an array (arr) delimited on =. If the first subscript of the array is j, print the second subscript.

Comments

0

There is lot of ways to do that in bash. The better depends on the strings pattern.

Assuming the pattern would always be key=value_without_whitespace key2=value2 ... a way could be:

echo "a=b c=d e=f g=h i=j j=k" | grep -P -o 'j=([^ ])' | cut -d '=' -f 2

Comments

0

Use source. pass semicolon separated string as file descriptor

source <(echo "a=b c=d e=f g=h i=j j=k" | tr ' ' ';')

echo $j

k

Comments

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.