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
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": ")[^"]*'
$ 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.