BASH syntax to extract a parameter from a string

bash

I'm not a BASH and/or grep/AWK expert so hoping somebody can quickly help me with this simple query. Consider the following string:

XenCenter.CustomFields.autostart: 120; last_shutdown_time:
20120418T11:24:32Z; last_shutdown_action: Destroy;
last_shutdown_initiator: external; last_shutdown_reason: halted;
import_task: OpaqueRef:1168d51a-e1ab-b02a-0db7-e6f9bd8fd269; mac_seed:
778079d8-5917-c5ce-4800-ee4321f3ed70

How do I extract the "120" bit above on the "autostart: 120" sub-string?

NOTE: the position and/or order of "XenCenter.CustomFields.autostart: 120" in the above string could and will change so can't rely upon it being the nth word

Best Answer

AWK supports custom record and field seperators (default are newline and whitespace respectably).

When I look at your string it is a combination of variables separted by ; and fields sperated by :

The following awk command sets these seperators (RS = record seperator, FS = field seperator) and checks if field 1 contains (the regex) "autostart" and prints the second field of the record:

awk 'BEGIN { RS=";" ; FS=": " } $1 ~ /autostart/ { print $2 }'

In a shell this produces:

$ echo $STRING | awk 'BEGIN { RS=";" ; FS=": " } $1 ~ /autostart/ { print $2 }'
120