繁体   English   中英

从文件中提取特定字符串,然后使用grep,awk,sed输出到另一个文件

[英]Extract a particular string from a file and output to another file using grep, awk, sed

我有一个文件,它包含ff字符串

2013-09-08 21:00:54 SMTP connection from [78.110.75.245]:5387 (TCP/IP connection count = 20)
2013-09-08 21:00:54 SMTP connection from [188.175.142.13]:34332 (TCP/IP connection count = 20)
2013-09-08 21:45:41 SMTP connection from [58.137.11.145]:51984 (TCP/IP connection count = 20)
2013-09-08 21:49:26 SMTP connection from [109.93.248.151]:22273 (TCP/IP connection count = 20)
2013-09-08 21:49:27 SMTP connection from [37.131.64.203]:7906 (TCP/IP connection count = 20)

我想做的是仅提取IP地址并将其保存到文件中。

我从这个开始

sed '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$' file > ips

但是我无法使它工作。

使用awk

awk -F'[][]' '{print $2}' log.file > addresses
78.110.75.245
188.175.142.13
58.137.11.145
109.93.248.151
37.131.64.203

实际上,我可能会使用jasonwryan解决方案,但要回答为什么您的sed命令不起作用的原因是,因为您使用的是扩展的正则表达式 ,甚至使用了与perl兼容的正则表达式。 要将ERE与sed一起使用,您需要使用-rGNU sed-E和BSD变体明确地将其打开。 但是sed不支持PCRE,但是您可以放弃使用非捕获组,因为这实际上并没有帮助。

由于您只是模式匹配,因此grep可能比sed更好:

$ grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' file
78.110.75.245
188.175.142.13
58.137.11.145
109.93.248.151
37.131.64.203  

请注意,锚点也需要删除,即^$因为要匹配的模式不是从字符串的开头或结尾开始。 grep在默认情况下也不支持扩展正则表达式,因此使用-E-o仅打印该行的匹配部分而不是整个行。

最后的问题是您刚刚提供了sed和正则表达式以及一个文件。 sed不是grep并且不会仅打印出匹配的行(尽管当然可以,但这不是您的操作方式) 一种方法是使用替代命令s替换IP之前的所有内容和IP之后的所有内容:

$ sed -r 's/.+[[]([^]]+).+/\1/' file
78.110.75.245
188.175.142.13
58.137.11.145
109.93.248.151
37.131.64.203

Regexplanation:

s    # sed substitute command 
/    # the delimiter marking the start of the regexp
.+   # one or more of any character
[    # start a character class
[    # character class contains a single opening square bracket 
]    # close character class (needed so single [ isn't treated as unclosed)
(    # start capture group
[    # start character class
^]+  # one or more character not an ]
]    # end character class
)    # end capture group 
.+   # one or more of any character
/    # the delimiter marking the end of the regexp and start of replacement
\1   # the first capture group
/    # the delimiter marking the end of the replacement 

是不同正则表达式风格的比较。

您可以使用sed将方括号[]中的内容进行匹配:

sed 's/.*\[\(.*\)\].*/\1/' log.file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM