Artificial intelligent assistant

bash script to extract string from last output line 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 | sort amzn-ami-2016.03.i-amazon-ecs-optimized ami-22a49541 amzn-ami-2016.03.j-amazon-ecs-optimized ami-862211e5 amzn-ami-2016.09.a-amazon-ecs-optimized ami-73407d10 amzn-ami-2016.09.b-amazon-ecs-optimized ami-5781be34 amzn-ami-2016.09.c-amazon-ecs-optimized ami-774b7314 <===== this line and to verify it is in the format ami-and-a-mix-of-alphanumeric else echo "bad string" and exit the script How can it be done?

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 1


To verify that it follows the right format, you may do


line="$( 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 1
fi


If 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 1
fi

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy 60e2b7ea9385628181785236cd75a695