Search for and display file names from a file
When you search from more than one file, it displays the file name by default:
The code is as follows:
grep "word" file name
grep root/etc/*
Sample output:
The code is as follows:
/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 part of the start of each line is the filename (for example,/etc/crontab,/etc/group). Use the-l option to display only file names:
The code is as follows:
Grep-l "string" filename
Grep-l root/etc/*
Sample output:
The code is as follows:
/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 also reverse the output; Use the-l option to output the file names of those files that do not match:
The code is as follows:
Grep-l "word" filename
Grep-l root/etc/*
Sample output:
The code is as follows:
/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
Find files based on file contents
Enter the following command:
The code is as follows:
grep ' String ' *.txt
grep ' Main (' *.c
grep ' #include ' *.c
grep ' getchar* ' *.c
Grep-i ' Ultra ' *.conf
Grep-ir ' Ultra ' *.conf
which
-I: Ignores patterns (matching strings valid, valid, valid) and input files (matching file.c file.c file. C) is case-insensitive.
-R: Recursively read all files in each directory.
Highlight match to the pattern
You can easily highlight patterns when searching for a large number of files:
The code is as follows:
$ grep--color=auto-ir ' GetChar (); ' *.c
Displays the file name and line number for the found pattern
You may need to display the file name and line number:
The code is as follows:
$ grep--color=auto-irnh ' GetChar (); ' *.c
which
-N: Adds a 1-based line number before each line in the output.
-H: Print file name for each match. This is the default option when you want to search for multiple files. (LCTT-H option forces hidden file names; the-L and-l options are used to display only matching/mismatched file names, while-H and-H are used to control the display/not display of file names before matching rows are displayed. )
The code is as follows:
$grep--color=auto-nh ' DIR ' *
Output Sample:
You can also use the Find command:
The code is as follows:
$ find. -name "*.C"-print | Xargs grep "Main ("