Shell:在yaml文件的子部分下获取特定单词

时间:2018-03-09 09:11:31

标签: bash shell awk sed grep

如何在yaml文件的name部分下获取metadata标记的值。

    apiVersion: v1
    kind: Pod
    metadata:
      name: sss-pod-four
      namespace: default
    spec:
      containers:
      - name: sss-test-container
        image: anaudiyal/infinite-loop
        volumeMounts:
        - mountPath: "/mnt/sss"
          name: sss-test-volume
      volumes:
        - name: sss-test-volume

我需要获得sss-pod-four字符串。

grep  "\sname: " config/pod.yaml | awk -F ": " '{print $2}'

以上代码正在打印 sss-pod-foursss-test-containersss-test-volume

3 个答案:

答案 0 :(得分:3)

请您试着跟随并告诉我这是否对您有帮助。

awk '/metadata/{flag=1} flag && /name:/{print $NF;flag=""}'  Input_file

现在添加非单线形式的解决方案,但现在也有解释:

awk '
/metadata/{         ##checking a string metadata in current line here and if it is TRUE then do following:
 flag=1}            ##Making a variable named flag value TRUE here.
flag && /name:/{    ##Checking if variable named flag is TRUE here and current line has string name: in it then do following:
  print $NF;        ##Printing the last column of the current line here.
  flag=""           ##Making variable named flag value as NULL here.
}
' Input_file        ##Mentioning Input_file name here.

答案 1 :(得分:3)

您也可以使用此sed命令来实现目标:

$ sed -n '/metadata:/,/spec:/p' input.yml | grep -oP '(?<=name: ).*'
sss-pod-four

答案 2 :(得分:1)

你也可以使用GNU grep:

grep -zoP '\n(\s*)metadata:(\n\1\s+.*)+name: \K.*' input.yml

-z标志在零字节上分割行,以便整个文件内容可以在单个正则表达式中匹配。 -o将让grep仅输出匹配,-P启用Perl样式正则表达式,这对于换行符匹配和\K是必需的,metadata:将输出限制为左侧后面的无换行符正则表达式部分。

我做的与其他解决方案有什么不同以及你能适应sed或awk的是我首先测量spec:行的缩进然后只继续匹配,而以下行的缩进更高,即使metadata:未跟随metadata:,即使name不包含{ "name": "Project Example", "short_name": "project", "icons": [{ "src": "images/icons/icon-128x128.png", "sizes": "128x128", "type": "image/png" }, { "src": "images/icons/icon-144x144.png", "sizes": "144x144", "type": "image/png" }, { "src": "images/icons/icon-152x152.png", "sizes": "152x152", "type": "image/png" }, { "src": "images/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "images/icons/icon-256x256.png", "sizes": "256x256", "type": "image/png" }], "start_url": "/index.html", "display": "standalone", "background_color": "#3E4EB8", "theme_color": "#2F3BA2" } 属性,它也能正常工作。