I have a sentence whic contains an IP address. For example,
This sentence contains an ip number 1.2.3.4 and port number 50, i want to print the IP address only.
From the above sentence, I want to print the IP address only. How can I do this? I heard that it is possible to do this with sed
It's possible, but not elegant:
[0-9]
matches any digit,\{1,3\}
means it can be repeated 1 to 3 times.\.
matches a dot. The whole IP is captured by the\(...\)
parentheses, what comes before and after is matched by.*
, i.e. anything repeated zero or more times. The whole matching string (i.e. the whole line) is then replaced by the contents of the first matching group.You can make it more readable by introducing a variable:
It prints the whole string if the IP is not found. It also doesn't check for invalid IPs like 256.512.999.666.
This is a
grep
solution:-o
print only the matching part-E
switches to extended regex[0-9]
) one or more times (+
) then a dot (\.
) and again digits...Here another solution with
perl
:-l
specified the line terminator (newline)-n
loops trough the input given byecho
(could be multiple lines)-e
code followsgrep
solution aboveUse this command of
grep
:Or even better:
or
I use grep:
This will print only valid ip adresses, unlike the other answers
I would do like this in python 3 interpreter. It not only grabs the text which are in this
111.111.111.111
format but also it checks for valid or not.To get the python 3 interpreter, type
python3
command on the terminal.Extension to choroba's answer:
If you don't want new line to be printed and you only want to print IP's:
Output:
Explanation:
AWK combined with RegExp is very appropriate for processing parts of lines.
Basic idea of the one-liner bellow is to for-loop through a line, and check for presence of four digits and dots, repeated at maximum 4 times; at the same time we can check for a digit repeated 2 to 4 times for port number
Sample run
Your sentence contains 50 and, together without separation, hence printed together, but with
gsub(/[[:punct:]]/,"")
that can be removed if desired.