How to grep string without filenames in Linux?


We know that we can make use of the grep command to search for a particular pattern of characters in all the lines of a file or multiple files. The grep command performs a case-insensitive search for words in a file.

Let’s see a simple example where we will grep a pattern in all the files that are present in a directory.

Command

grep -i ‘lp’ Sample*

Output

Sample: The sample was printed via the internet.
Sample: I believe lp cares about what the device is.
Sample1: This was printed via the internet.
Sample1: I believe lp cares about what the device is.
Sample2: This was printed via the internet.
Sample3: I believe lp cares about what the device is.

The only concern for this particular scenario is that we don’t want the filename to be printed along with the output. We simply want the string where a particular pattern is found and we just need to print that string.

In that case we can use the -h parameter which can be used to hide the filenames.

Command

grep -i -hn ‘lp’ Sample*

According to the Linux Docs, the -h flag does the following,

“-h, --no-filename

Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.”

Output

The sample was printed via the internet.
I Believe lp cares about what the device is.
This was printed via the internet.
I believe lp cares about what the device is.
This was printed via the internet.
I believe lp doesn't care what the device is

Updated on: 30-Jul-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements