Printing the last field on the last line

2 bash shell awk grep sed

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
Run Code Online (Sandbox Code Playgroud)

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).

Chr*_*our 5

You can do this easily with awk:

$ your_command | awk 'END{print $NF}' 
127.0.0.1
Run Code Online (Sandbox Code Playgroud)

To store to a file use the redirection operator:

$ your_command | awk 'END{print $NF}' > my_ip
Run Code Online (Sandbox Code Playgroud)

InawkEND在读取输入后执行,因此我们正在查看输入中的最后一行。NF是一个特殊awk变量,包含当前行上的字段数(本例中为 4),其中默认字段分隔符为空格。该$装置打印字段值,即{print $1}打印第一个字段值、$2第二个字段值等。


一种方法是sed

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

# save to file
$ your_command | sed -n '3s/.*: //p' > my_ip
Run Code Online (Sandbox Code Playgroud)

该选项-n关闭每行的默认打印。这3是我们要操作的行的地址(行号) 。我们想要对冒号之前的所有内容(后跟空格)执行替换(s 命令),并将其替换为空字符串。正斜杠是所选的分隔符,是打印命令,因此在替换发生后仅打印第三行。.*:p


使用grep-o选项,您可以打印给定 IP 匹配正则表达式的所有匹配项:

$ 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
Run Code Online (Sandbox Code Playgroud)

Linux 上最好的解决方案是使用hostname

$ hostname -I
127.0.0.1

# save to file
$ hostname -I > my_ip
Run Code Online (Sandbox Code Playgroud)

然而,这不是可移植的,因为该-I选项在 OSX 版本的命令中可用hostname