Grep string from map object

Viewed 101

I'm trying to extract each username value in clients object and store in array (bash). However, grep failed to match even through matched in regex101.com

//a.txt
username = "fakeuservalue"

clients = [
  {
    username = "user1"
  },
  {
    username = "user2"
  }
]


x=$(cat a.txt | grep -e 'username\s+=\s+\"(.*)\"')
echo $x

Any clues? I'm also try to add another check on "clients" object so that skip retrieve "fakeuservalue".

3 Answers

You can use

x=$(sed -n '/^clients = \[/,/^]$/s/.*username *= *"\(.*\)".*/\1/p' a.txt)

See the online demo:

#!/bin/bash
s='username = "fakeuservalue"

clients = [
  {
    username = "user1"
  },
  {
    username = "user2"
  }
]'
sed -n '/^clients = \[/,/^]$/s/.*username *= *"\(.*\)".*/\1/p' <<< "$s"

Output:

user1
user2

1. Extract username values using grep

grep -oP '(?<=username = ")[^"]*' a.txt

2. Assign username values into array arr1.

readarray -t arr1 <<< $(grep -oP '(?<=username = ")[^"]*' a.txt)

3. Print all array arr1 elements

printf "%s\n" ${arr1[@]}

4. Print first and last elements in array arr1 having 3 elements

echo "${arr1[0]}"
echo "${arr[2]}"

If sed is an option, you can use;

$ x=($(sed -n '/clients = \[/,/]/{/username/s/.*= "\([^"]*\)"/\1/p}' a.txt))
$ echo ${x[0]}
user1
$ echo ${x[1]}
user2
Related