Grep用于具有多种模式和多种选项的多重搜索

时间:2016-05-10 06:50:45

标签: grep pattern-matching

以下是内容:

client_name:
client_since:
client_address:
client_city:
client_country_code:
contact_number:
       <some number 1>
       <some number 2>
client_account_number:
client_bank_name:

我需要使用“ client_name:”,“ client_city:”,“ client_country_code :”模式/字符串打印行。我还需要打印“ contact_number:”&amp;之后有2行,这样就可以打印出2条动态线条。

如何通过单线命令实现这一目标?

2 个答案:

答案 0 :(得分:0)

$ cat data 
client_name:
client_since:
client_address:
client_city:
client_country_code:
contact_number:
       landline:
       mobile:
client_account_number:
client_bank_name:
$ egrep '^(contact_number|\s*landline|\s*mobile|client_(name|city|country_code))' data 
client_name:
client_city:
client_country_code:
contact_number:
       landline:
       mobile:
$

答案 1 :(得分:0)

grep -E "client_name:|client_city:|client_country_code:|contact_number:|landline:|mobile:" data
client_name:
client_city:
client_country_code:
contact_number:
       landline:
       mobile:

如果联系号码下面的两行是动态的,那么您可以使用以下grep combo:

     grep -E "client_name:|client_city:|client_country_code:" data  && grep -A2 "contact_number:" data
client_name:
client_city:
client_country_code:
contact_number:
       landline:
       mobile:

grep -E "client_name:|client_city:|client_country_code:|`grep -A2 contact_number: data`" data

这是实现评论中要求的一种肮脏方式:

grep -Ee "client_name:|client_city:|client_country_code:|`awk '/contact_number/{print; nr[NR+2]; next}; NR in nr' data`" data
client_name:
client_city:
client_country_code:
contact_number:
       mobile: