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

Time:01-20

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

grep -l 'hello' *

Given these files:

test1

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?

CodePudding user response:

Like this:

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

CodePudding user response:

This task is more suited to awk.

awk 'FNR == 1 {p=""; next}
     p ~ /hello/ {print FILENAME; nextfile}
     {p = $0}' test*

test2

There is no need to loop and call external utilities sed, grep multiple times for each iteration.

CodePudding user response:

You can solve this by using the following code:

grep 'hello' test* | tail -n  2 | head -n -1
  • Related