Home > Mobile >  Grep string from map object
Grep string from map object

Time:04-19

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".

CodePudding user response:

You can use

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

See the online demo:

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

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

Output:

user1
user2

CodePudding user response:

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]}"

CodePudding user response:

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