1

I have a long string and from that string I want to extract a value of a key and store it in a variable. I want to extract value of userName from abc string. I tried below code but it say's file name too long error.

abc="Create [newSystem=System [identityDomain=bbundlesystemser201201-test, admin=AdminUser [firstName=BSystemAdminGivenName, middleName=null, lastName=BSystemAdminFalilyName, userName=bbundlesystemadminusername, password=*******, email=hello@example.com], idmConsoleURL=https://abc.com.jspx, sftpHost=d910.abc.com, sftpUser=3pyylzoo, sftpPwd=*******]]"
echo $abc
sed -n 's/^userName= //p' "$abc"

Is there anything wrong I am doing? I want to extract value of userName and store it in a variable.

userName=bbundlesystemadminusername
peterh
  • 11,875
  • 18
  • 85
  • 108
flash
  • 1,455
  • 11
  • 61
  • 132

2 Answers2

2

You can use BASH regex matching:

[[ $abc =~ userName=([^][,[:space:]]+) ]] && userName="${BASH_REMATCH[1]}"
echo "$userName"

bbundlesystemadminusername

Or else, you can use this sed command:

userName=$(sed 's/.*userName=\([^][,[:space:]]*\).*/\1/' <<< "$abc")
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Note that this doesn't work for all fields in the OP's input. Try it with `email` and `sftpPwd`. I've accounted for that in the regex in my answer. – ghoti Aug 10 '18 at 20:07
  • I would suggest `[[ $abc =~ email=([^][,[:space:]]+) ]] && echo "${BASH_REMATCH[1]}"` – anubhava Aug 10 '18 at 20:12
2

I think I'd do this with an associative array and process substitution in bash 4:

$ declare -A a
$ while IFS== read k v; do a["$k"]="$v"; done < <(grep -oEi '[a-z]+=[^], ]+' <<<"$abc")
$ printf '%q\n' "${a[userName]}"
bbundlesystemadminusername

While this doesn't properly respect the data structure of your input variable, it does recognize key=value pairs and save them in an easily accessible array, using only a single grep -o to split the string into the KV pairs. The nice this about this is of course that you've got the rest of the data also available to you, should you want to avoid unnecessary calls to grep or awk or sed or whatever.

Note that associative arrays were added to bash in version 4. If you're doing this in macOS (or indeed in a POSIX shell), it'll have to be adjusted.

ghoti
  • 45,319
  • 8
  • 65
  • 104