How to get string from file in bash?

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

2 answers

  • answered 2019-02-10 13:49 NiteRain

    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
    

  • answered 2019-02-11 02:22 tshiono

    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.