簡體   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