简体   繁体   English

bash +如何从行捕获IP地址

[英]bash + how to capture IP address from line

I have many configuration files , the line that start with LINE word have IP address 我有许多配置文件,以LINE字开头的行具有IP地址

My target to read the line that start with LINE word from the file and print only the IP address 我的目标是从文件中读取以LINE单词开头的行,并仅打印IP地址

The problem is that IP address can be in any field in the line so I can't capture the IP according to field number 问题是IP地址可以在该行的任何字段中,因此我无法根据字段号捕获IP

example

grep LINE file1.txt

LINE /home/Ariate/run.pl "Voda STS 4 Test -  " "102841" && ssh 17.77.170.130 -p 2022 



grep LINE file2.txt

LINE /home/Ariate/run.pl 137.77.170.30 "Voda STS 4 Test -  " "102841" && ssh  ACTIVE

please advice how to capture the IP address from the line ( solution can be also with perl one liner ) 请提出如何从线路中捕获IP地址的建议(解决方案也可以使用perl一种衬垫)

expected results 预期成绩

echo $IP_FROM_LINE

17.77.170.130



echo $IP_FROM_LINE

137.77.170.30
perl -MRegexp::Common=net -lne 'print $1 if /^LINE.*\b($RE{net}{IPv4})/'

Using this grep -oE : 使用此grep -oE

grep -oE '\d+\.\d+\.\d+\.\d+' file
17.77.170.130
137.77.170.30

OR else: 要不然:

grep -oP '\d+\.\d+\.\d+\.\d+' file
grep -oE '[0-9]{2,3}(\.[0-9]{2,3}){3}'

matches 火柴

17.77.170.130
137.77.170.30

or 要么

grep -oP '\d{2}(\.\d{2}){3}'

if your grep supports -P option. 如果您的grep支持-P选项。

both of them works with the data you have given. 它们都可以使用您提供的数据。

But if you want really worried of what to be matched, use 但是,如果您真的担心要匹配什么,请使用

grep -Eo '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'

which would match excat ip addresses. 可以匹配exat ip地址。

The following will get you the desired IP addresses: 以下将为您提供所需的IP地址:

grep -oP '^LINE.*\b\K\d+\.\d+\.\d+\.\d+' file

To place the result in a variable as request, you'll need to iterate of the results as follows: 要将结果作为请求放入变量中,您需要按以下步骤迭代结果:

grep -oP '^LINE.*\b\K\d+\.\d+\.\d+\.\d+' file |
while read IP_FROM_LINE ; do
    echo $IP_FROM_LINE
done

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

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