user2151985
user2151985

Reputation:

Printing the last field on the last line

So there's an application that tells me what's my current IP. Instead of just printing the IP, the output is:

Starting GetIP process...
Getting your IP...
Your current IP: 127.0.0.1

Is there a way to just save the IP to a file? Either by removing first 2 lines and beginning of the third, or by just saving the actual numbers and dots.

I know I can trim down the first two lines with sed but how do I remove the text on the third line? (By the way, expected output is just the IP, no colons or whitespaces).

Upvotes: 2

Views: 1785

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85775

You can do this easily with awk:

$ your_command | awk 'END{print $NF}' 
127.0.0.1

To store to a file use the redirection operator:

$ your_command | awk 'END{print $NF}' > my_ip

In awk the END block is executed after the input has been read so we are looking at the last line in the input. NF is a special awk variable that contains the number of fields on the current line (so 4 in this case) where the default field separator is whitespace. The $ means print the field value i.e. {print $1} prints the first field value $2 the second ect.


One way with sed:

$ your_command | sed -n '3s/.*: //p' 
127.0.0.1

# save to file
$ your_command | sed -n '3s/.*: //p' > my_ip

The option -n turns off the defaulting printing of every line. The 3 is address (the line number) of the line we want to operate on. We want to perform a substitution (the s command) for everything .* upto the colon followed by a space : and replace it with an empty string. The forward slashes are the chosen delimiters and the p is the print command so only the third line is printed after the substitution has taken place.


Using grep and the -o option you can print all matches of a given IP matching regular expression:

$ your_command | egrep -o '([0-9]{1,3}[.]){3}[0-9]{1,3}$'

# save to file
$ your_command | egrep -o '([0-9]{1,3}[.]){3}[0-9]{1,3}$' > my_ip

The best solution on Linux would be to use hostname:

$ hostname -I
127.0.0.1

# save to file
$ hostname -I > my_ip

This isn't portable however as the -I option is available with the OSX version of the hostname command.

Upvotes: 5

Related Questions