I run the following command:

aws ec2 describe-instances --filters "Name=ip-address,Values=MY_IP" | grep InstanceId 

and I get:

"InstanceId": "i-b0f13081",

How can I only get the following:

i-b0f13081

This is what I tried:

 aws ec2 describe-instances --filters "Name=ip-address,Values=MY_IP" | grep InstanceId | gawk -F: '{ print $2 }' 
 "i-b0f13081", 
share|improve this question
up vote 3 down vote accepted

awk:

Set " as field delimiter, and get the 4th field:

% awk -F'"' '{print $4}' <<<'"InstanceId": "i-b0f13081",'
i-b0f13081

Similarly cut:

% cut -d'"' -f4 <<<'"InstanceId": "i-b0f13081",'
i-b0f13081

grep with PCRE (-P):

% grep -Po ':\s*"\K[^"]+' <<<'"InstanceId": "i-b0f13081",'
i-b0f13081

Shell parameter expansion:

% var='"InstanceId": "i-b0f13081",'
% var="${var%\"*}"
% echo "${var##*\"}"
i-b0f13081

sed:

% sed -E 's/^[^:]+:[^"]+"([^"]+).*/\1/' <<<'"InstanceId": "i-b0f13081",'
i-b0f13081

perl:

% perl -pe 's/^[^:]+:[^"]+"([^"]+).*/$1/' <<<'"InstanceId": "i-b0f13081",'
i-b0f13081

python:

% python -c 'import sys; print sys.stdin.read().split("\"")[3]' <<<'"InstanceId": "i-b0f13081",'
i-b0f13081
share|improve this answer
1  
Nice answer.... – Elder Geek Oct 20 '16 at 18:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.