Reputation: 35
I would like to extract the IP v4 address only from my /etc/hosts file with shell sed command.
I managed to isolate those line with localhost at the end of the line with the following command:
$ sed -E '/localhost$/!d ' host_1 | sed -n 1p
which gave me the following output :
# 127.0.0.1 localhost
How can I only extract the IP v4 address alone form the above result?
Upvotes: 1
Views: 1890
Reputation:
Late but you can try this :
sed -E '/localhost$/!d ' host_1 | sed -n 1p | sed -r 's/\localhost//g'
The last part replaces the grep used by 4everLRG
If you need to extract localhost IP from /etc/hosts make sure to replace host_1 with /etc/hosts
Upvotes: 0
Reputation: 37394
The test data:
$ cat file
127.0.0.1 localhost
# 127.0.0.2 localhost
127 127.0.0.3 localhost
The sed:
$ sed -n 's/\(.*[^0-9]\|\)\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\).*/\2/p' file
The output:
127.0.0.1
127.0.0.2
127.0.0.3
The sed with the -E
switch:
$ sed -nE 's/(.*[^0-9]|)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*/\2/p' file
Upvotes: 1
Reputation: 1011
sed -E '/localhost$/!d ' /etc/hosts | awk '{print $1}' | grep -v :
Upvotes: 0
Reputation: 35
I tried this command and it works fine.
$ sed -E '/localhost$/!d' host_1 | sed -n 1p |grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
output: 127.0.0.1
Nonetheless I am still curious about how can I substitute the grep by a sed command.
Upvotes: 0