Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I skip the first and last line while using grep?

I am using grep to find any files that contain the word "hello" in the current directory:

grep -l 'hello' *

Given these files:

test1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

hello
hi
how are you
stuff

test2

welcome
hello
etc

test3

hey
there
hello

The output is:

test1
test2
test3

However, I want to search these files for the word "hello", but skip the first and last lines, so my output is:

test2

I know I can use the following command to ignore the first and last lines:

sed '1d;$d' *

But is there any way to use this with grep, so that it ignores the first and last line of each file? If not, how exactly can I use grep to skip the first and last line of each file?

>Solution :

Like this:

for file in *; do sed '1d;$d' "$file" | grep -q hello && echo "$file"; done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading