[英]how to output paragraphs with spaces from a file using unix/linux 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
一起使用,您需要使用-r
和GNU 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.