-1

I have file that is not JSON and I want to get string of 'name' from the file but only name with key type with value 'typeX' Input :

ID : id
mySer:
   - name : xyz
     type : typeX

myServ2:
   - name : wyz
    params:
     - name :ppp

Output

name : xyz
or xyz

I tried

awk '/"name":/{flag=1;next}/^$/{flag=0}flag'

but I got all the names

user1365697
  • 5,819
  • 15
  • 60
  • 96
  • 1
    It is not a json – user1365697 Feb 10 '19 at 12:29
  • Please add example data to your question, plus the desired output – hek2mgl Feb 10 '19 at 12:32
  • @hek2mgl - I updated the question – user1365697 Feb 10 '19 at 12:34
  • Looks like yaml – hek2mgl Feb 10 '19 at 12:36
  • yes it is yaml and I need it with bash script – user1365697 Feb 10 '19 at 12:36
  • 2
    Sorry, why do you ask 'I need to parse something which is not JSON' instead of 'How to parse yaml'? That doesn't make sense for me. I'm sure you'll find answers if you search for `How to parse yaml from bash` – hek2mgl Feb 10 '19 at 12:37
  • 1
    Take a look at `man grep`. `grep -B 1 'type : typeX$' file | grep -Po '\Kname : xyz$'` – Cyrus Feb 10 '19 at 12:45
  • Possible duplicate of [How can I parse a YAML file from a Linux shell script?](https://stackoverflow.com/questions/5014632/how-can-i-parse-a-yaml-file-from-a-linux-shell-script) – e.dan Feb 10 '19 at 13:53
  • 1
    Most *good* answers for the question "how to parse yams from bash" are going to suggest not using `bash`; I'm not aware of any good standalone programs for parsing Yaml (like `jq` does for JSON). `grep`, `awk`, `sed`, etc do not qualify as "good standalone programs for parsing Yaml". – chepner Feb 10 '19 at 18:58

2 Answers2

1

If yq is available, please try:

yq -r '.[][]? | select (.type == "typeX") | .name' file.yml

output:

xyz

file.xml looks like:

ID : id
mySer:
   - name : xyz
     type : typeX

myServ2:
   - name : wyz
     params:
     - name :ppp

(The posted file looks like improperly indented in the line of params.)

In most platform you can install yq with:

$ pip install yp

Before using yq, you also have to install its dependency, jq.

tshiono
  • 21,248
  • 2
  • 14
  • 22
0

test.yml:

ID : id
mySer:
   - name : xyz
     type : typeX

myServ2:
   - name : wyz
    params:
     - name :ppp
myExample:
   - name : levi
     type : typeX

test.sh:

#!/bin/bash

str=`cat test.yml`;


function match {
    MATCHES=() 
    local mstr=$1 re="($2)(.*)"
    while [[ -n $mstr && $mstr =~ $re ]]; do
        MATCHES+=("${BASH_REMATCH[1]}")
        mstr=${BASH_REMATCH[2]}
    done
}

match "$str" 'name : [a-zA-Z0-9]+\s+type : typeX' 

for (( v=0; v < ${#MATCHES[@]}; v++)); do
    echo ":: ${MATCHES[$v]}";
done

The output:

:: name : xyz
     type : typeX
:: name : levi
     type : typeX

However, if you only want to see the name lines, you can pipe that into grep ( | grep name ) where you only show name and then the output would look like this:

:: name : xyz
:: name : levi
NiteRain
  • 663
  • 8
  • 14