0

I have a file named.conf, here first i need to find himanshu.com and then extract the corresponding zone file i.e. for1 , I don't know what parameters would be passed to the awk script to find pattern two lines below.

named.conf

options {


directory "/var/named";

};



zone "himanshu.com" in {
type master;
file "for1";
};

zone "0.168.192.in-addr.arpa" in {
type master;
file "rev";
};
3
  • grep -A2 himanshu.com named.conf|awk '{print $2} Commented Jun 5, 2014 at 13:54
  • 1
    @Gaius -A2 shows 2 lines below/after matching, not the 2nd line below matching. Commented Jun 5, 2014 at 14:00
  • Plus, the file line might not be exactly 2 below the zone line. If this were true, you could do grep -A2 himanshu.com named.conf | grep file | cut -d\" -f2 Commented Jun 5, 2014 at 15:41

4 Answers 4

1

Using awk:

$ awk '/himanshu.com/ {found=1} /^file/ && found {print $0; exit}' file
file "for1";

This command sets a flag called found when it sees himanshu.com and then prints out the file if the flag has been set.

Another way using sed:

$ sed  -n '/himanshu/,/}/{/^file/s/.*\"\(.*\)\".*$/\1/p}' file
for1

This command first gets all lines between himanshu and the next } (inclusive), then searches for file within that block and finally uses a regex to extract the name of the file.

Sign up to request clarification or add additional context in comments.

2 Comments

this is a clever solution. it should work for OP's requirement. there is one exception, if in himanshu block, no file occurs, the awk and sed line may output the wrong file name. As I said, it may not be the case that OP should take care about.
that's easily fixed in the sed commmand, using sed -n '/himanshu/,/}/ to grab the whole block. (answer updated)
1
$ awk -v RS="" -F'\n' '/zone "himanshu.com"/{for(i=1;i<=NF;i++)if($i~/^file /)print $i}' file
file "for1";

the above line will first focus on the zone "himanshu.com" block, then extract the file ... line. no matter it locates how many line after the zone "hi..." line.

1 Comment

I would add that if your zone "him..." block contained empty lines, the solution will fail.
0

Try this awk command,

$ awk '/zone "himanshu.com"/ {getline; getline; print;}' file
file "for1";

OR

Run the below command to get the exact file name,

$ awk '/zone "himanshu.com"/ {getline; getline; print $2}' file
"for1";

$ awk '/zone "himanshu.com"/ {getline; getline; gsub (/";/,"",$2); gsub (/^"/,"",$2); print $2}' file
for1

Comments

0

awk variation:

awk -F\" '$1~/zone/ && $2==s, /}/ {if($1~/file/) print $2}' s=himanshu.com file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.