簡體   English   中英

使 awk 打印單行的特定段

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM