-1

I have a file test.txt

---
kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
subjects:
roleRef:
  kind: ClusterRole
  name: bla

And need this output with sed (just the line that matches the exact pattern)

kind: ClusterRole
metadata:

sed -n '/kind: ClusterRole/,/metadata/p' test.txt

kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
  kind: ClusterRole
  name: bla

is showing ClusterRole, ClusterRoleBinding and additional indented ClusterRole

sed -n '/kind: ClusterRole\b/,/metadata/p' test.txt
sed -n '/\<kind: ClusterRole\>/,/metadata/p' test.txt

Both of the above output to nothing what am I doing wrong? just so it's clear and I'm not getting any grep -B 2 suggestions ;-) this is an example file, the original file is a lot bigger and has hundreds of ClusterRoles so I need to figure out how to match the exact pattern.

Thank you!

lema

lema
  • 80
  • 6
  • It's not very clear why you would want to do this (you don't need sed to produce the output as described). However: `sed -n '/^kind: ClusterRole$/,${1,/^metadata:$/p}' file.txt` – jhnc Feb 15 '20 at 02:33
  • or `sed -n '/^kind: ClusterRole$/,${p;/^metadata:$/q}' file.txt` to not waste time reading the rest of the file – jhnc Feb 15 '20 at 02:42

3 Answers3

0

If you just need to search the exact multiple lines, then you can achieve it using pcregrep

pcregrep -M 'kind: ClusterRole(\n)metadata:' test.txt

where -M, --multiline allow patterns to match more than one line.

More details can be found in this SO post.

Edit:

You can also use grep

grep -Pazo 'kind: ClusterRole\nmetadata:' test.txt

Reference: this SO post

Nitish
  • 597
  • 1
  • 4
  • 9
0

You should include start-of-line (^) and end-of-line ($) in your pattern.

Walter A
  • 19,067
  • 2
  • 23
  • 43
0

This might work for you (GNU sed):

sed -n 'N;/^kind: ClusterRole\nmetadata:$/p;D' file

Append the next line and print the lines if it matches. Delete the first line and repeat.

If you only want the first match, use:

sed -n 'N;/^kind: ClusterRole\nmetadata:$/{p;q};D' file
potong
  • 55,640
  • 6
  • 51
  • 83