-1

I need to get the IP from a log I need to grep the true-client and after that I need to grep true-client-ip=[191.168.171.15] and get just the IP

2019.02.14-08:26:06:713,asd:1234:chan,0.000,asd,S,request-begin-site,POST,{remoteHost=1.2.3.4,remoteAddr=1.2.3.4,requestType=POST,serverName=api=[text/html],accept-charset=[iso-12345-15, utf-8;q=0.5, *;q=0.5],accept-encoding=[gzip],server-origin=[5],cache-control=[no-cache, max-age=0],pragma=[no-cache],program-header=[true],te=[chunked;q=1.0],true-client-ip=[191.168.171.15],true-host=[www.server.com]

I was trying grep -o "true-client-ip=[^ ]*," but it brings me:

true-client-ip=[191.168.171.15],true-host=[www.server.com]

I need just true-client-ip=[191.168.171.15] so I can cut after to bring get the IP like true-client-ip=[191.168.171.15] | cut -d= -f2

Tanktalus
  • 21,664
  • 5
  • 41
  • 68

2 Answers2

1

Using grep -P flag if available :

grep -oP 'true-client-ip=\[\K[^]]*'

Perl's \K meta-character discards what precedes when displaying the result, so it will match the "true-client-ip=[" part but only display the IP.

If grep -P isn't available, I would use sed :

sed -nE 's/.*true-client-ip=\[([^]]*).*/\1/p'
Aaron
  • 24,009
  • 2
  • 33
  • 57
  • Yeah, `\K` is handy :) – Til Feb 14 '19 at 16:04
  • 1
    @Tiw sure is, a shame it isn't implemented in more PCRE-based regex engines – Aaron Feb 14 '19 at 16:05
  • What do you mean by PCRE-based engines? Boost is based on PCRE, and it has `\K` support. Onigmo has `\K` support (Ruby regex engine), but Onigmo is not PCRE based. – Wiktor Stribiżew Feb 14 '19 at 16:31
  • @WiktorStribiżew I was thinking about languages which implement regex derived from PCRE such as Java and Python, both of which compare their implementation to Perl's but do not implement `\K`. Was my phrasing confusing, or do you think most PCRE-derived regex implementations implement `\K` ? – Aaron Feb 14 '19 at 16:36
  • They are not based on PCRE, they are quite different. Even from each other. They are compared to Perl regex, because it has been there long before, but not PCRE. – Wiktor Stribiżew Feb 14 '19 at 16:39
  • @WiktorStribiżew Yeah, I guess I meant to say PCRE-derived, I didn't intend to imply the implementation itself was based on Perl's. – Aaron Feb 14 '19 at 16:41
  • 2
    Probably, "Perl-inspired" is a better term here. – Wiktor Stribiżew Feb 14 '19 at 17:01
1

If you have GNU grep, you can do it like this:

$ grep -oP "(?<=true-client-ip=\[)[^\]]*" file
191.168.171.15

The (?<=) is called Positive Lookbehind, which you can find related doc here.
The backslash \ in [^\]] is actually unnecessary, I just feel like to add it to make it more intuitive, less misleading-prone :-) .

Til
  • 5,150
  • 13
  • 26
  • 34