1

I am trying to get a specific output using grep but I am unable to do so. Here is my grep command :

crictl inspect 47aaecb541688accf37840108cc0d19b39b84f8337740edf2ca7e5e81a24328e | grep "io.kubernetes.pod.namespace"

The output of the above command is "io.kubernetes.pod.namespace": "kube-system",

I even tried crictl inspect 47aaecb541688accf37840108cc0d19b39b84f8337740edf2ca7e5e81a24328e | grep -Po '(?<="io.kubernetes.pod.namespace": ").*' but the output i got is kube-system",

I just want the value i.e just kube-system

How do I modify my grep command. Thanks for the help

kms
  • 153
  • 2
  • 9
  • 3
    `grep` is the wrong tool. `crictl ... | awk '/io.kubernetes.pod.namespace/ { print $4 }' FS=\"` – William Pursell Sep 20 '19 at 19:32
  • 1
    or `awk -F\" '/io.kubernetes.pod.namespace/{print $4}'` – William Pursell Sep 20 '19 at 19:34
  • Try `cut -f 2 -d ':'` instead of `grep`. – jww Sep 20 '19 at 22:12
  • 4
    Possible duplicate of [How to get the second column from command output?](https://stackoverflow.com/q/16136943/608639), [Select a particular column using awk or cut or perl](https://stackoverflow.com/q/13795196/608639), [How can I get 2nd and third column in tab delim file in bash?](https://stackoverflow.com/q/6312564/608639), [Extracting columns from text file with different delimiters in Linux](https://stackoverflow.com/q/19959746/608639), etc. – jww Sep 20 '19 at 22:13

1 Answers1

1

Using grep

We need to make just one small change to the grep -P command. Your command was:

$ echo '"io.kubernetes.pod.namespace": "kube-system",' | grep  -Po '(?<="io.kubernetes.pod.namespace": ").*'
kube-system",

We just need to replace .* (which matches everything to the end of the line) with [^"]* with matches everything up to but not including the first ":

$ echo '"io.kubernetes.pod.namespace": "kube-system",' | grep  -Po '(?<="io.kubernetes.pod.namespace": ")[^"]*'
kube-system

Or, using your crictl command:

crictl inspect 47aaecb541688accf37840108cc0d19b39b84f8337740edf2ca7e5e81a24328e | grep  -Po '(?<="io.kubernetes.pod.namespace": ")[^"]*'

Using sed

$ echo '"io.kubernetes.pod.namespace": "kube-system",' | sed -n '/"io.kubernetes.pod.namespace"/{s/.*": "//; s/".*//p}'
kube-system

How it works:

  • -n tells sed not to print unless we explicitly ask it to.

  • /"io.kubernetes.pod.namespace"/{...} selects only those lines that contain "io.kubernetes.pod.namespace" and performs the commands in braces on them.

  • s/.*": "// removes everything from the beginning of the line to the last occurrence of ": ".

  • s/".*//p removes everything from the first remaining " to the end of the line and prints the result.

John1024
  • 109,961
  • 14
  • 137
  • 171