简体   繁体   中英

Grep first string matching regex

I want to get the first string that matches my regular expression. For example I have the String

RCPT from unknown[211.147.3.74]: 450 4.7.1 Client host rejected: cannot find your hostname, [211.147.3.74];

and my script looks like this:

IP=`echo $LINE | grep -E -o --max-count=1 '(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]?)'`

echo $IP

As result I get

211.147.3.74 211.147.3.74

But I would like to get the IP only once. I tried 'grep --max-count=1' but there are still two ip's.

LINE='RCPT from unknown[211.147.3.74]: 450 4.7.1 Client host rejected: cannot find your hostname, [211.147.3.74];'
ipn='(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
IP=`echo $LINE | grep -E -o "$ipn\.$ipn\.$ipn\.$ipn" | head -1`
echo "$IP"

or from here

echo "$LINE"  | perl -MRegexp::Common=net -ne '/($RE{net}{IPv4})/ and print "$1\n"'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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