[英]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.