Home > Net >  Script to save bash output to YAML file
Script to save bash output to YAML file

Time:11-22

I can output the relevant details of my printer using the command line: sed -En 's/[ \t]*b?(id[vp][^ \t]*|endpoint)(address)?[ \t] ([^ \t]*).* (out|in)?.*/\l\1\4 (\3)/Ip' <(lsusb | awk '$0 ~ /STMicroelectronics printer-80/{print $6}' | xargs -I % sh -c "lsusb -vvv -d %") outputs:

idVendor (0x0483)
idProduct (0x5743)
endpointOUT (0x01)
endpointIN (0x81)

Now, I need to save those data to a YAML file in the following format:

printer:
        type: Usb
        idVendor: 0x0483
        idProduct: 0x5743
        in_ep: 0x81
        out_ep: 0x01

I just don’t know how to achieve this formatting and save to the file.

I‘ve tried formatting the output, but couldn’t get further than this snippet.

CodePudding user response:

This reformats each line:

sed -E 's/(.*) \((.*)\)/    \1: \2/g' <<< "idVendor (0x0483)"

result:

    idVendor: 0x0483

Combine this with your previous command and prepend the printer: line to get the desired output:

echo "printer:" > file.yaml
sed -En 's/[ \t]*b?(id[vp][^ \t]*|endpoint)(address)?[ \t] ([^ \t]*).* (out|in)?.*/\l\1\4 (\3)/Ip' \
    <(lsusb | awk '$0 ~ /STMicroelectronics printer-80/{print $6}' | \
      xargs -I % sh -c "lsusb -vvv -d %"\
    ) | sed -E 's/(.*) \((.*)\)/    \1: \2/g' >> file.yaml

It is unclear how you want to get the line type: Usb, you can of course just write it into the file like printer:. As for the different names, simply append sed -e 's/endpointOUT/out_ep/' -e s/endpointIN/in_ep/'.

  • Related