0

I need to parse a text file which contains multiple lines of IP information but i want to extract the IP Address but exclude the subnet with CIDR using grep and a regex expression.

Sample text rows:

Removed host entry 10.43.160.72 @10.43.160.64/26-> esjc-test-sr90p
Removed host entry 10.26.232.157 @10.26.232.0/22-> esjc-test-sr90p

Desired output :

10.43.160.72
10.26.232.157

Currently im using :

grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" test

But this also includes the subnet information i want to avoid .

Thanks!

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Ruben G
  • 11
  • 4

2 Answers2

2

1st solution: With your shown samples, could you please try following. Written and tested with GNU grep.

grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}(\s|$)' Input_file | cut -d' ' -f1


2nd solution: In case you are ok with awk, could you please try following.

awk '{for(i=1;i<=NF;i++){if($i~/^([0-9]+\.){3}[0-9]+$/){print $i}}}' Input_file

OR with OP's used regex(with little tweak in it) try following:

awk '{for(i=1;i<=NF;i++){if($i~/^(([0-9]{1,3})\.){3}[0-9]{1,3}$/){print $i}}}' Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

$ cut -d' ' -f4 file
10.43.160.72
10.26.232.157
Ed Morton
  • 188,023
  • 17
  • 78
  • 185