[英]Make awk print a specific segment of a single line
我有一个名为 LogsDocker 的文件,其中包含
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/root/.docker/machine/machines/Main-hola"
export DOCKER_MACHINE_NAME="Main-hola"
# Run this command to configure your shell:
# eval $(docker-machine env Main-hola)
我只想打印ip
192.168.99.100
刚刚发现了 awk 和命令
awk 'BEGIN { FS = "//"} ; { print $2}' LogsDocker
使它打印(带有一堆空行)
192.168.99.100:2376"
只打印没有空行的 ip 的正确方法是什么
你能不能试试以下。
awk '/DOCKER_HOST/ && match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/){print substr($0,RSTART,RLENGTH)}' Input_file
说明:为上述代码添加说明。
awk ' ##Starting awk program from here.
/DOCKER_HOST/ && match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/){ ##Checking condition if string DOCKER_HOST is found in line AND match is having a mentioned regex matched in it.
print substr($0,RSTART,RLENGTH) ##If above conditions are TRUE then printing substring whose starting index is RSTART and ending index is RLENGTH.
}
' Input_file ##Mentioning Input_file name here.
第二种解决方案:考虑到您的 Input_file 将始终相同,然后尝试遵循。
awk -F'[/:]' '/DOCKER_HOST/{print $4}' Input_file
说明:为上述代码添加说明。
awk -F'[/:]' ' ##Starting awk program from here and setting field separator as /or colon here.
/DOCKER_HOST/{ ##Checking condition if a line has string DOCKER_HOST then do following.
print $4 ##Printing 4th field of current line.
}
' Input_file ##Mentioning Input_file name here.
第三种解决方案: sed
解决方案。
sed -n '/DOCKER_HOST/s/.*\///;s/:.*//p' Input_file
说明:以下仅作说明之用。
sed -n ' ##Starting sed program from here and making printing off for all lines until specifically mentioned.
/DOCKER_HOST/ ##Searching string DOCKER_HOST in lines if present then do following.
s/ ##s means perform substitution operation here.
.*\/ ##mentioning regex which covers everything till / in line, if matched this regex
// ##Then substitute it with NULL here.
; ##semi colon denotes to segregate another substitute operation after this one.
s/ ##Doing substitution from here.
:.* ##Match everything from : to till last of line.
// ##Substitute above matched values with NULL in current line.
p ##p means only print this line.
' Input_file ##Mentioning Input_file name here.
假设给定您现有的代码,IP 地址是您拥有的唯一位置//
:
$ awk 'sub(/.*\/\//,""){sub(/:.*/,""); print}' file
192.168.99.100
或做出其他假设...:
$ awk -F'//|:' 'NF>2{print $3}' file
192.168.99.100
或者:
$ awk -F'//|:' '/DOCKER_HOST=/{print $3}' file
192.168.99.100
或者 ....
这实际上只取决于该文件中还有什么内容以及您希望它有多健壮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.