简体   繁体   中英

Store perl regex capture groups in bash variables

I'm writing a small bash script to get the status of certain hardware through our api.

curl -sG ip:port/device/status -o temp.txt

I use a curl command to get the status and write to a temp file

I played around with different regex types, the simple bash regex was not enough and ended up using perl.

perl -nle 'printf("'%-15s' \t '%-15s' \t '%-15s' \t '%-15s' \n", "$1", "$2", "$3", "$4") while m{regex_to_capture_data}g' temp.txt

My regex capture is working and prints out perfectly (some of the iterations will have blank capture groups, which is important info, and that prints as expected)

is there a way to have arrays populate with those capture groups and use them further in my bash script?

say for instance $1, $2, $3, $4 were fields device_id, uptime, status, last_error. and in my curl command I have info of 4 devices. I would like to have device_id[0] up to [device_id[3], and the same for each capture group.

I'm not experienced with perl, and only used it as suggested by a few forum posts, so any advice on how to achieve this would be greatly appreciated.

Your example code is obviously broken; you can't nest single quotes; though Perl provides the convenience operator q() so you can easily work around this. The formatting has other errors, too. Probably you mean something like

perl -nle 'print(join("\t", "$1", "$2", "$3", "$4"), "\n") while m{regex_to_capture_data}g' temp.txt

You can pipe this to

while IFS=$'\t' read -r boulders rubble stones rocks; do
    ...

though probably you could just run the body of whatever that loop was doing from Perl directly, too.

perl -nle 'system("geologee", "--boulders", $1, "--rubbleUrl", "$2:$3/$4") while m{regex_to_capture_data}g' temp.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM