Need to Extract String from Result of awk Command and Copy to Output File

I want to extract strings from a terraform.tfstate file.

I am running the following ack command:

awk '/nifi1a/{x=1}x&&/private_ip/{print;exit}' terraform.tfstate

Running this command results in:

"private_ip": "",

I would like to extract the string between the second set of double quotes i.e., and copy this to an out put file.

Can someone provide guidance/recommendations on how to do this?

Asked By: David S


Instead of print you can split the string and print only the required part:

awk '/nifi1a/{x=1}x&&/private_ip/{split($0,a,"""); print a[4];exit}' terraform.tfstate

If you want to create second command to work on result you can use command:

awk '/nifi1a/{x=1}x&&/private_ip/{print;exit}' terraform.tfstate | awk -F" '{print $4}'

The idea is to use double quote " as delimiter and split $0 in array. And then print only one element of array.

If you want to add hostname the command will be:

awk '/nifi1a/{x=1}x&&/private_ip/{split($0,a,"""); print a[4], "nifi1a";exit}' terraform.tfstate >>/etc/hosts
Answered By: Romeo Ninov

Chances are all you need is:

awk -F'"' '/nifi1a/{f=1} f && /private_ip/{print $4; exit}' terraform.tfstate

but without sample input that’s just a guess and the original part of the code may not be optimal, there may be some better (more concise, portable, robust, etc.) way to do what you want.

Don’t assume people reading your questions will know what a "a terraform.tfstate file" or any other input format is, always show us concise, testable sample input and expected output so we can best help you.

Answered By: Ed Morton
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.