簡體   English   中英

AWK:將匹配模式與字段分隔符連接起來

[英]AWK: Concatenate matching pattern with a field separator

輸入文件:

cat /tmp/filename

app_name="MysqlCluster"
whatever whatever
whatever whatever
whatever whatever
whatever whatever
region="Europe"

預期產量:

MysqlCluster_Europe

嘗試:

root@localhost:~# awk -F\" '/app_name|region/ {printf "%s_", $2}' /tmp/filename
MysqlCluster_Europe_root@localhost:~# 

root@localhost:~# awk -F\" '/app_name|region/ {OFS="_"; printf "%s", $2}' /tmp/filename
MysqlClusterEuroperoot@localhost:~#

root@localhost:~# awk -F\" '/app_name|region/ {printf "%s_", $2} END{print} ' /tmp/filename
MysqlCluster_Europe_

And few other attempts on similar lines but have not been successful.

我在尋找:

root@localhost:~# awk <here goes some awk magic> /tmp/filename
MysqlCluster_Europe    <<< NOTE: No Underscore at the end

以下將適用於您的示例。 (雖然它不會打印換行符。)

awk -F\" '/^(app_name|region)/ { printf "%s%s", s, $2; s="_" }' /tmp/filename

不要減少你的努力,但是在兩個單獨的動作中處理app_nameregion會更實用,這樣它也將支持多個app_name-region對。

awk -F\" '/^app_name/ { printf "%s_", $2 } /^region/ { print $2 }' /tmp/filename

使用GNU awk。 即使文件中有更多app_name-region對,這也應該有效:

$ awk '
/^(app_name|region)=/ {                     # look for matching records
    a[++c][1]                               # initialize 2d array 
    split($0,a[c],"\"")                     # split on quote
}
END {                                       # after processing file(s)
    for(i=1;i in a;i++)                     # loop all stored values
        printf "%s%s",a[i][2],(i%2?"_":ORS) # output
}' file
MysqlCluster_Europe

這是一個正則表達式匹配column1中的app_name和區域,然后用“=”字符分割。

awk '$1 ~ "app_name|region" {split($0,a,"="); printf a[2]}' /tmp/filename | sed 's/"//g'

sed刪除雙引號。

BR

$ awk -F'=?"' '{f[$1]=$2} $1=="region"{print f["app_name"] "_" $2}' file
MysqlCluster_Europe

你可以嘗試一下。

awk -F'"' '/app_name/{val=$(NF-1);next} /region/{print val "_" $(NF-1)}'  Input_file

輸出如下。

MysqlCluster_Europe

說明:現在為上面的代碼添加說明。

awk -F'"' '                 ##Setting field separator as " here for all lines.
/app_name/{                 ##Checking condition if a line has string app_name then do following.
  val=$(NF-1)               ##Creating variable named val whose value is 2nd last field of current line.
  next                      ##Using next keyword will skip all further statements from here.
}                           ##Closing block for this condition here.
/region/{                   ##Checking condition if a line has string region then do following.
  print val "_" $(NF-1)     ##Printing variable val and OFS and $(NF-1) here.
  val=""                    ##Nullifying variable val here.
}
'  Input_file               ##Mentioning Input_file name here.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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