Grep From Files and Display the File Name On Linux or Unix System

Posted on in Categories , , last updated May 3, 2017

How do I grep from a number of files and display the file name only?

When there is more than one file to search it will display file name by default:

grep "word" filename
grep root /etc/*

Sample outputs:

/etc/bash.bashrc:       See "man sudo_root" for details.
/etc/crontab:17 *       * * *   root    cd / && run-parts --report /etc/cron.hourly
/etc/crontab:25 6       * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
/etc/crontab:47 6       * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
/etc/crontab:52 6       1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
/etc/group:root:x:0:
grep: /etc/gshadow: Permission denied
/etc/logrotate.conf:    create 0664 root utmp
/etc/logrotate.conf:    create 0660 root utmp

The first name is file name (e.g., /etc/crontab, /etc/group). The -l option will only print filename if th

grep -l "string" filename
grep -l root /etc/*

Sample outputs:

/etc/aliases
/etc/arpwatch.conf
grep: /etc/at.deny: Permission denied
/etc/bash.bashrc
/etc/bash_completion
/etc/ca-certificates.conf
/etc/crontab
/etc/group

You can suppress normal output; instead print the name of each input file from which no output would normally have been printed:

grep -L "word" filename
grep -L root /etc/*

Sample outputs:

/etc/apm
/etc/apparmor
/etc/apparmor.d
/etc/apport
/etc/apt
/etc/avahi
/etc/bash_completion.d
/etc/bindresvport.blacklist
/etc/blkid.conf
/etc/bluetooth
/etc/bogofilter.cf
/etc/bonobo-activation
/etc/brlapi.key

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

13 comment

      1. what about
        grep -rI “whatever” ./ | cut -d: -f1 | sort -u

        nb it will fail on file containing “:” such as some perl man pages but…

        …Or just add some proper form
        for i in `ls` ; do
        grep -q “whatever” “$i” && echo “$i”
        done

  1. how do I know the location and file name form the result that grep shows?
    I use command like cat * | grep
    Now what I need is the location of the file name along withe the grep result.

    Help anyone

Leave a Comment