Home > Blockchain >  how to parse data in yaml from column to row
how to parse data in yaml from column to row

Time:11-29

My final data after parsing from a yaml file is like this in text file :

        - id: 200
          addr: 10.242.57.129/27
        - id: 210
          addr: 10.242.57.161/25
        - id: 300
          addr: 10.244.26.1/24

I wanted to convert to this and save it as txt with shell scripting ( bash):

200,10.242.57.125,27
210,10.242.57.162,25
300,10.244.26.11,24 

Can anyone help for that?

Need to get the command shell for this (with awk, grep , sed , ...).

I used the following code but it doesn't work:

grep -F -e "id:" | cut -c 14-16 -e "addr:" | cut -c 16-35 ip.txt | paste -d , - -

CodePudding user response:

Using GNU sed

$ sed -E '/-/{N;s~[^0-9]*([0-9] )\n[^0-9]*([0-9.] )/([0-9] )~\1,\2,\3~}' input_file
200,10.242.57.129,27
210,10.242.57.161,25
300,10.244.26.1,24

CodePudding user response:

Given that the question is also tagged powershell, let me offer a native PowerShell solution that uses the switch statement, whose features resemble that of awk:

switch -Regex -File file.txt {
  '\bid: (\d )'            { $id = $Matches.1  }
  '\baddr: ([\d.] )/(\d )' { '{0},{1},{2}' -f $id, $Matches.1, $Matches.2  }
}

CodePudding user response:

This might work for you (GNU sed):

sed 'N;s/[^0-9.\n/]//g;y/\n\//,,/' file

Append the next line.

Remove all but id and address.

Replace the newline and / with ,'s.

  • Related