繁体   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