我有文件“test_file.txt”。我的输出必须包含
文件中的所有“IP 地址”和“2017 年月份” test_file.txt
。
Server$
Server$cat test_file.txt
IP ADDRESS:
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19
NEKI TEXT 2
1 one
2 two
3 three
4 four
5 five
MONTHS OF 2017:
01. January 2017
02. February 2017
03. March 2017
04. April 2017
05. May 2017
06. June 2017
07. July 2017
08. August 2017
09. September 2017
10. October 2017
11. November 2017
12. December 2017
Server$
我发现,egrep
命令但输出不包含文件中的所有 12 个月。
Server$egrep -A3 "ADDRESS|MONTHS" test_file.txt
IP ADDRESS:
1 172.17.17.17
2 172.17.17.18
3 72.17.17.19
--
MONTHS OF 2017
01. January 2017
02. February2017
03. March 2017
Server$
我如何执行输出中可以有 3 个 IP 地址和 12 个月的命令?
答案1
我会awk
用段落模式(通过取消设置记录分隔符):
$ awk -vRS= '/^(IP ADDRESS|MONTHS)/' test_file.txt
IP ADDRESS:
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19
MONTHS OF 2017:
01. January 2017
02. February 2017
03. March 2017
04. April 2017
05. May 2017
06. June 2017
07. July 2017
08. August 2017
09. September 2017
10. October 2017
11. November 2017
12. December 2017
Perl 具有相同的功能:
perl -00 -ne 'print if /^IP ADDRESS/ or /^MONTHS/' test_file.txt
答案2
只需做两次egrep
:
egrep -A3 "ADDRESS" test_file.txt && egrep -A12 "MONTHS" test_file.txt
解释 :
egrep -An
将匹配该词(和他的台词)并采取n感谢-A
选项,该词下的线条
test_file.txt
是我们要提取这些行的文件
"ADDRESS"
并"MONTHS"
搜索""
语句内的单词
&&
只需逐个执行每个命令(但如果第一个命令不起作用,则第二个命令就不会完成!)
答案3
这很简单。您可以使用以下命令。
grep -E "172|01" file.sh
输出如下:
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19
MONTHS OF 2017:
01. January 2017
02. February 2017
03. March 2017
04. April 2017
05. May 2017
06. June 2017
07. July 2017
08. August 2017
09. September 2017
10. October 2017
11. November 2017
12. December 2017
解释:
如果你grep
只为172
那么输出将是
$ grep "172" file.sh
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19
如果你grep
只为01
,那么
$ grep "01" file.sh
MONTHS OF 2017:
01. January 2017
02. February 2017
03. March 2017
04. April 2017
05. May 2017
06. June 2017
07. July 2017
08. August 2017
09. September 2017
10. October 2017
11. November 2017
12. December 2017
因此,您需要同时使用这两个。要搜索多个模式,我们需要使用管道元字符 ( |
),并且由于这是扩展正则表达式的一部分,因此我们需要该-E
选项。
要了解该grep
命令的更多选项,您可以查找这篇文章是我写的有帮助的。