awk or sed or grep filter a line and/or between strings

Hi, I have multiple files on a directory with the following content:

blahblah
blahblah
hostname server1
blahblah
blahblah
---BEGIN---
aaa
bbb
ccc
ddd
---END---
blahblah
blahblah
blahblah

I would like to filter all the files with awk or sed or something else so I can get below output

hostname server1
---BEGIN---
aaa
bbb
ccc
ddd
---END---

I can do awk '/---BEGIN---/,/---END---/' * but I don't get the hostname server1 line.
I have hundreds of file so the 'hostname server1' would at least give me some idea from which file is the output coming from.
Ideally I would get

hostname server1
---BEGIN---
...
---END---
hostname server2
---BEGIN---
...
---END---
...

Any suggestion on how can I achieve this?

One way:

awk '/---BEGIN---/,/---END---/ {
  if ( !F[FILENAME]++ ) print H " " FILENAME
  print $0
}' H=${HOSTNAME:-$(hostname)} *
1 Like

I received a PM that my post is not clear, I'm sorry about that so I would like to update my post as below.

I mentioned that I have hundreds files, probably let's just start with one file.

I have a file, filename is config.txt and below is the content

I would like to filter using awk or sed and get something like below

Your post seemed perfectly clear to me, even thought I misread it! It seems you want just the hostname, not the filename.

awk '/---BEGIN---/,/---END---/ {
  if ( !F[H]++ ) print "hostname " H
  print $0
}' H=${HOSTNAME:-$(hostname)} file*

If you're pulling these files from multiple hosts, you might want to add the hostname to the filename or in the file itself.

1 Like

Yep, the 'hostname' has same value as the 'filename' in my case so that does not really matter I think.

I'm still learning Linux ans I was expecting a one liner command. Apparently I need to learn more about script/bash scripting based on your reply.
I'll do more reading and practicing on awk and bash script.
Thanks Scott!

If I understand your post correctly, you might want to try:

awk '/^hostname /;/---BEGIN---/,/---END---/' file*
2 Likes

That works perfectly! Thanks Don Cragun :slight_smile: