Maurice Amar
Maurice Amar

Reputation: 139

how to print Lines Between Two Patterns in file using SED or AWK?

I have a problem to print the selection of a file between 2 lines using exact strings i.e. "###" and not "####"

I have tried to select a part of a text in file but I can't reach to obtain the wanted selection

by running the command:

sed -ne "/MULTIPLE-RESOURCES/,/###/p" kubernetes_commands.md

### MULTIPLE-RESOURCES

#### Viewing Resource Information

> kubectl get svc, po
> kubectl get deploy, no
> kubectl get all
> kubectl get all --all-namespaces

## KUBECTL

###

> kubectl run -i --tty busybox --image=busybox --restart=Never -- sh

from this text, I expect to have:

### MULTIPLE-RESOURCES

#### Viewing Resource Information

> kubectl get svc, po
> kubectl get deploy, no
> kubectl get all
> kubectl get all --all-namespaces

## KUBECTL

but the actual result is:

### MULTIPLE-RESOURCES

#### Viewing Resource Information

Upvotes: 1

Views: 529

Answers (4)

melpomene
melpomene

Reputation: 85757

Here's a straightforward solution using perl:

perl -ne 'print if /MULTIPLE-RESOURCES/ .. s/^###\n//'

The main point is anchoring the ### pattern to the beginning (^) and end (\n) of the line. Replacing it by nothing also ensures that the final ### line is not printed itself.

Upvotes: 1

anubhava
anubhava

Reputation: 784918

You may use this sed:

sed -n '/MULTIPLE-RESOURCES/,/^###$/ { /###$/!p; }' file

### MULTIPLE-RESOURCES

#### Viewing Resource Information

> kubectl get svc, po
> kubectl get deploy, no
> kubectl get all
> kubectl get all --all-namespaces

## KUBECTL

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133428

Could you please try following.

awk '/^### |^###$/{if(++count==1){found=1} else {found=""}} found' Input_file

Upvotes: 0

Kent
Kent

Reputation: 195029

What you can try is:

sed -n '/MULTI/,/^## KUBE/p' file

Upvotes: 0

Related Questions