简体   繁体   中英

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 ie "###" 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

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

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.

您可以尝试的是:

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

您可以尝试以下吗?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM