-1

My text format is

synchronised to server (192.168.204.1) at stratum 5

I want to extract the ip address in between the bracket and the text before it .like

synchronised to server (192.168.204.1)

what is the regular expression .(using awk or grep )

mubir
  • 193
  • 2
  • 7
  • for given sample `grep -o '.*)'` would work.. if that doesn't solve your real use case, change your sample... also, you are expected to show what you have tried yourself to solve this.. https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean could help you with learning regex, but note that regex syntax/feature differs from tool to tool.. see documentation of respective tools for details – Sundeep Jul 17 '18 at 08:23
  • This looks trivial, but it works: awk -F'at' ' {print $1} ' Input_File – AHT Jul 17 '18 at 08:35
  • Try `sed 's/\(([^)]*)\).*/\1/' <<< str` – revo Jul 17 '18 at 09:32
  • Possible duplicate of [How do you extract IP addresses from files using a regex in a linux shell?](https://stackoverflow.com/questions/427979/how-do-you-extract-ip-addresses-from-files-using-a-regex-in-a-linux-shell) – tripleee Jul 17 '18 at 12:34

3 Answers3

0

If your actual Input_file is same as shown samples then following may help you here.

awk 'match($0,/.*\([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\)/){print substr($0,RSTART,RLENGTH)}'  Input_file
RavinderSingh13
  • 101,958
  • 9
  • 41
  • 77
0

Would you consider using sed to do that? Here's the command you may tried

sed -r 's#(.*\([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}\)).*#\1#' Input_File

Brief explanation,

  1. The regex .*\([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}\) would match anything ahead to (IP address). Noted that the inner brackets shall be escaped.
  2. \1 would only print the matched part embraced by the outer brackets.
CWLiu
  • 3,563
  • 1
  • 7
  • 12
-1

Try this!

.*\b([0-9]{1,3}\.){3}[0-9]{1,3}\b\)

Breakdown :

.* selects all of the text before the IP address

\b matches a word boundary between a word character and a non-word character.
([0-9]{1,3}\.) matches numbers 0-9 a total of 1-3 times (to make 1.1.1.1 and 127.0.0.1 a valid IP address) and then matches a period.
{3} matches 3 times the token above.
[0-9]{1,3} matches numbers 0-9 a total of 1-3 times.
\b is a word boundary
\) matches parenthesis

AutoBootDisk
  • 73
  • 14
  • Please add explanation. – juzraai Jul 17 '18 at 15:32
  • 1
    done! Also why do StackOverflow answers get so many downvotes if the solution works? – AutoBootDisk Jul 17 '18 at 15:58
  • 1
    Because the point is the *quality of the answer* and not just to drop in a solution. :) Take the time to write an answer, add explanation, add reference links if possible, and you'll get positive scores. I advise you to surf a bit and check answers with high votes. Take my upvote as a motivation. :) – juzraai Jul 17 '18 at 16:17