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

How do I grep from a number of files and display the file name only? How do I force the grep command to display the filename before the matching lines in its output?

When there is more than one file to search it will display file name by default. Consider the following grep command:

ADVERTISEMENTS

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 the match found by the grep:

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

How to display filename before matching line in grep

By default grep display filename if you provide multiple filenames. For example:
grep 'foo' file1 file2
grep '192.168.2.254' /etc/hosts /etc/resolv.conf
grep -n '192.168.2.254' /etc/hosts /etc/resolv.conf

####################################################
## Always show filename headers with output lines.##
## Works with BSD/macOS/GNU/Linux grep version ##
####################################################
grep -H 'search-word' filename1 filename2
grep '192.168.2.254' /etc/hosts /dev/null
##########################
### gnu/Linux grep only ##
##########################
grep --with-filename 'foo' file1 file2
grep --with-filename '192.168.2.253' /etc/{hosts,resolv.conf}

Linux grep display filename before matching line

Linux grep display filename before matching line

grep show filename before matching line

In this example, I need to search for ‘http://www.cyberciti.biz’ in all files and display matched filenames only, run:
grep -l -R 'http://www.cyberciti.biz'
Now replace all occurrences of ‘http://www.cyberciti.biz’ with ‘https://www.cyberciti.biz’ using the sed command:

## get filenames ##
files=$(grep -l -R 'http://www.cyberciti.biz' . )
echo "$files"
## replace using sed ##
for f in $files
do
   sed -i 's+http://www.cyberciti.biz+https://www.cyberciti.biz+g' "$f"
done

Conclusion – Grep from files and display the file name

Let us summaries all the grep command option in Linux or Unix:

  1. grep -l 'word' file1 file2 : Display the file name on Linux and Unix instead of normal output
  2. grep -L 'string' file1 file2 : Suppress normal output and show filenames from which no output would normally have been printed
  3. grep -n 'string' filename : Force grep to add prefix each line of output with the line number within its input file
  4. grep --with-filename 'word' file OR grep -H 'bar' file1 file2 file3: Print the file name for each match
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
13 comments… add one
  • Josh Keife Sep 30, 2010 @ 17:35

    for i in `ls` ; do
    grep -q “whatever” $i && echo $i
    done

    • 🐧 nixCraft Oct 1, 2010 @ 5:42

      Why ls? It will fail when you have file names with white spaces. A better way is to use wild cards:

      for i in * ; do
      grep -q “whatever” $i && echo $i
      done
      • lUser Feb 20, 2011 @ 20:19

        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

  • Josh Keife Sep 30, 2010 @ 17:41

    or if you need to search all file and subdirs within a dir you can run the commands above. Just replace `ls` with `find . -type f`.

  • mlathe Oct 2, 2010 @ 0:45

    Or better yet, use xargs.
    find . -type f | xargs grep html

    If you want to deal with spaces etc…
    find . -type f | xargs -I {} grep -H foo "{}"

    • yoander (sedlav) Oct 13, 2010 @ 17:36

      Dealing with space with a shorter form
      find . -type f -print0 | xargs -0 grep foo

  • layman Oct 19, 2010 @ 7:46

    I agree, find is working great for me.


    find -name *.log -uid 1000

    You can find files only owned by uid. Nifty feature.

  • Becky Gawat Mar 19, 2012 @ 18:55

    How do I grep if i am looking for a specfic percentage?
    grep -w “68%-100% /usr/local/stage”

    thanks in advance

  • willywonker May 3, 2012 @ 20:44

    ls | while read FILE; do echo “$FILE” done;

    This handles whitespace and other nasties nicely.

  • avinash Jun 7, 2012 @ 17:22

    how can i grep
    CA
    from filename AUZ_CA_EL.txt

    • BrianBlaze Nov 27, 2012 @ 17:09

      cat AUZ_CA_EL.txt | grep “CA”

  • Özzesh Dec 5, 2012 @ 7:45

    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

  • a Jan 11, 2014 @ 22:54

    THX for the “$FILE” solution! Worther than 100 webpages!

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.