How to extract a text part by regexp in linux shell? Lets say, I have a file where in every line is an IP address, but on a different position. What is the simplest way to extract those IP addresses using common unix command-line tools?
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- JQ: Select when attribute value exists in a bash a
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
You can use sed. But if you know perl, that might be easier, and more useful to know in the long run:
Most of the examples here will match on 999.999.999.999 which is not technically a valid IP address.
The following will match on only valid IP addresses (including network and broadcast addresses).
Omit the -o if you want to see the entire line that matched.
grep -E -o "([0-9]{1,3}[.]){3}[0-9]{1,3}"
for centos6.3
ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | awk 'BEGIN {FS=":"} {print $2}'
I wrote a little script to see my log files better, it's nothing special, but might help a lot of the people who are learning perl. It does DNS lookups on the IP addresses after it extracts them.
Everyone here is using really long-handed regular expressions but actually understanding the regex of POSIX will allow you to use a small
grep
command like this for printing IP addresses.(Side note) This doesn't ignore invalid IPs but it is very simple.