This bash script tries to get the string ami-774b7314 from the output of the following command so that it can be used as input to another command in the same script:  aws ec2 describe-images --region ap-southeast-2 --owners amazon --output text --query 'Images[].{A1name:Name,A2id:ImageId}' --filters Name=is-public,Values=true,Name=name,Values=amzn-ami-*.*.*-amazon-ecs-optimized | sortamzn-ami-2016.03.i-amazon-ecs-optimized ami-22a49541amzn-ami-2016.03.j-amazon-ecs-optimized ami-862211e5amzn-ami-2016.09.a-amazon-ecs-optimized ami-73407d10amzn-ami-2016.09.b-amazon-ecs-optimized ami-5781be34amzn-ami-2016.09.c-amazon-ecs-optimized ami-774b7314 <===== this lineand to verify it is in the format ami-and-a-mix-of-alphanumeric else echo bad string and exit the scriptHow can it be done?
bash script to extract string from last output line
bash;text processing
The tail command may be used for this. It gives you the last few (10 by default) lines of input as output (the tail of it).With the -n flag you may specify exactly how much of the tail you'd like to have:aws ec2 ... | sort | tail -n 1To verify that it follows the right format, you may doline=$( aws ec2 ... | sort | tail -n 1 )if [[ ! $line =~ ^amzn-ami-[0-9]{4}\.[0-9]{2}\.[a-z]-amazon-ecs-optimized\ ami-[0-9a-z]{8}$ ]]; then    echo bad string    exit 1fiIf you only want the last bit of the last line, use cut to cut it out:line=$( aws ec2 ... | sort | tail -n 1 | cut -d ' ' -f 2 )The -d ' ' -f 2 bit says use space as the field delimiter and give me the second field.Then the regular expression becomes shorter too:if [[ ! $line =~ ^ami-[0-9a-z]{8}$ ]]; then    echo bad string    exit 1fi