开发者

Filter text based in a multiline match criteria

I have the following sed command. I need to execute the below command in single line

cat File | sed -n '      
/NetworkName/ {
N
/\n.*ims3/ p
}' | sed -n 1p | awk -F"=" '{print $2}'

I need to execute the above command in si开发者_如何学运维ngle line. can anyone please help.

Assume that the contents of the File is

System.DomainName=shayam
System.Addresses=Fr6
System.Trusted=Yes
System.Infrastructure=No
System.NetworkName=AS
System.DomainName=ims5.com
System.DomainName=Ram
System.Addresses=Fr9
System.Trusted=Yes
System.Infrastructure=No
System.NetworkName=Peer
System.DomainName=ims7.com
System.DomainName=mani
System.Addresses=Hello
System.Trusted=Yes
System.Infrastructure=No
System.NetworkName=Peer
System.DomainName=ims3.com

And after executing the command you will get only peer as the output. Can anyone please help me out?


You can use a single nawk command. And you can lost the useless cat

nawk -F"=" '/NetworkName/{n=$2;getline;if($2~/ims3/){print n} }' file

You can use sed as well as proposed by others, but i prefer less regex and less clutter. The above save the value of the network name to "n". Then, get the next line and check the 2nd field against "ims3". If matched, then print the value of "n".


Put that code in a separate .sh file, and run it as your single-line command.


cat File | sed -n '/NetworkName/ { N; /\n.*ims3/ p }' | sed -n 1p | awk -F"=" '{print $2}'


Assuming that you want the network name for the domain ims3, this command line works without sed:

grep -B 1 ims3 File | head -n 1 | awk -F"=" '{print $2}'


So, you want the network name where the domain name on the following line includes 'ims3', and not the one where the following line includes 'ims7' (even though the network names in the example are the same).

sed -n '/NetworkName/{N;/ims3/{s/.*NetworkName=\(.*\)\n.*/\1/p;};}' File

This avoids abuse of felines, too (not to mention reducing the number of commands executed).

Tested on MacOS X 10.6.4, but there's no reason to think it won't work elsewhere too.


However, empirical evidence shows that Solaris sed is different from MacOS sed. It can all be done in one sed command, but it needs three lines:

sed -n '/NetworkName/{N
/ims3/{s/.*NetworkName=\(.*\)\n.*/\1/p;}
}' File

Tested on Solaris 10.


You just need to put -e pretty much everywhere you'd break the command at a newline or have a semicolon. You don't need the extra call to sed or awk or cat.

sed -n -e '/NetworkName/ {' -e 'N' -e '/\n.*ims3/ s/[^\n]*=\(.*\).*/\1/P' -e '}' File
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜