ukhlof
ukhlof

Reputation: 21

Bash grep ip from line

I have the file ip.txt which contain the following

ata001dcfe16f85.mm.ph.ph.cox.net (24.252.231.220)
220.231.252.24.xxx.com (24.252.231.220)

and I made this bash command to extract ips :

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]?)' ip.txt | sort -u > good.txt

I want to edit the code so it extracts the ips between the parentheses ONLY . not all the ips on the line because the current code extract the ip 220.231.252.24

Upvotes: 1

Views: 307

Answers (2)

Jotne
Jotne

Reputation: 41460

You can try awk

awk  -F"[()]" '{print $(NF-1)}' file
24.252.231.220
24.252.231.220

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26687

To get the IP within paranthesis all you need is to wrap the entire regex in an escaped \( \)

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]?)\)'

will give output as

(24.252.231.220)
(24.252.231.220)

if you want to get rid of the paranthesis as well in the output, look around would be usefull

grep -oP '(?<=\()(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]?)(?=\))'

would produce output as

24.252.231.220
24.252.231.220

a much more lighter version would be

grep -oP '(?<=\()(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)){3}(?=\))'

here

[0-9]{2} matches the number 2 times

(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)){3} matches . followed by 3 digit number three times

The repeating lines can be removed using a pipe to uniq as

grep -oP '(?<=\()(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]{2}?)){3}(?=\))' input | uniq

giving the output as

24.252.231.220

Upvotes: 2

Related Questions