2

I want to list the files that contain a pattern, without outputting the line(s) containing the pattern.  I assume that it's possible to do this with grep.  How should I use grep in that sense?  For example, the following command gives all the lines containing "stringpattern" (case insensitive) in all the .txt files.  I want to have only the name of the file (± the line number).

grep -ni stringpattern *.txt

Ideally, if the string/pattern is present more than once in one file, I would like to have multiple lines of output for that file.

2
  • And if the string is present more than once in one file? Do you want the output to show multiple lines for that file (each line with the same filename, but a different line number), or one line with the filename and the line numbers concatenated?
    – Edward
    Commented Jan 30, 2022 at 14:30
  • many thanks for your comment @Edward. Yes ideally i would like to have multiple lines for that file
    – ecjb
    Commented Jan 30, 2022 at 14:43

2 Answers 2

5

If you need only files that match:

grep -lie pattern -- *.txt

I don't think that you can use only grep to print only files and line numbers, because with option -n, it outputs on every line 'file:line:match'. If the file names don't contain : nor newline characters, you can though pipe this to cut to get only what you want.

grep -nie pattern -- /dev/null *.txt | cut -d: -f 1,2

The /dev/null is needed for the case where *.txt expanded to only one filename where grep then would otherwise not print the file name. With the GNU implementation of grep or compatible, you can use the -H / --with-filename instead to ensure the file name is always printed.

2
  • 1
    At least as long as the filenames don't contain colons, but in that case the output of grep -n is ambiguous anyway, sigh. Something like awk '/pattern/ { print FNR, FILENAME }' *.txt could also perhaps be used. (Still ambiguous if the names have newlines, sigh^2)
    – ilkkachu
    Commented Jan 30, 2022 at 14:44
  • Indeed @ilkkachu it also works well. many thanks
    – ecjb
    Commented Jan 31, 2022 at 9:52
1
awk '/pattern/{print FILENAME}' *.txt
1
  • Indeed @PraveenKumarBS it also works well. many thanks
    – ecjb
    Commented Jan 31, 2022 at 9:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .