AWK:使用字段分隔符连接匹配模式

时间:2018-11-29 11:10:00

标签: linux bash awk sed

输入文件:

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

5 个答案:

答案 0 :(得分:4)

以下内容适用于您的示例。 (尽管它不会打印换行符。)

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

在两个单独的操作中处理app_nameregion完全不会减少您的工作量,这将是更实际的imo,这样它也将支持多个app_name-region对。

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

答案 1 :(得分:3)

使用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

答案 2 :(得分:2)

此处带有正则表达式,以匹配列1中的app_name和区域,然后以“ =”字符分隔。

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

sed删除双引号。

BR

答案 3 :(得分:2)

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

答案 4 :(得分:0)

请您尝试一次。

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.