从跟随某个字符的行获取字符串

时间:2016-10-22 03:00:20

标签: bash packer

从文件中我使用以下cmd检索最后一行;

tail -n 1 build.log

输出如下:

1477101542,,ui,say,--> amazon-ebs: AMIs were created:\n\nus-east-1: ami-63237174\nus-west-1: ami-21236841\nus-west-2: ami-27872347

我尝试在us-east-1:us-west-1:&之后获取字符串us-west-2使用以下grep命令:

echo | tail -n 1 build.log | egrep -m1 -oe 'us-east-1: ami-.{8}' |  egrep -m1 -oe 'ami-.{8}'

我为每个条件运行此cmd三次。有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

如果区域出现的顺序是固定的,您只需执行以下操作:

$ echo | tail -n 1 build.log | egrep -o  'ami-.{8}'
ami-63237174
ami-21236841
ami-27872347

如果您要提取地区名称并且您有 GNU grep,请尝试:

$ echo | tail -n 1 build.log | grep -Po 'us-[^:]+(?=: ami-.{8})'
us-east-1
us-west-1
us-west-2

获取两个区域名称和相关值:

$ echo | tail -n 1 build.log | egrep -o 'us-[^:]+: ami-.{8}'
us-east-1: ami-63237174
us-west-1: ami-21236841
us-west-2: ami-27872347