grep command is used to search files. The basic syntax is:
Tutorial details | |
---|---|
Difficulty | Easy (rss) |
Root privileges | No |
Requirements | grep+Terminal |
Time | 1m |
grep 'word1 word2' file1 file2
grep [option] 'word1 word2' file1 file2
The -n or --line-number grep option
You can pass either -n or --line-number option to the grep command to prefix each line of output with the line number within its input file. The syntax is:
grep -n 'patten' file
grep -n 'patten' file1 file2
grep -n [options] 'pattens' file
In this example search for a patter/word called ‘/dev’ in /etc/fstab file and display line number while displaying the output on screen:
grep -n '/dev' /etc/fstab
Sample outputs:
6:# Accessible filesystems, by reference, are maintained under '/dev/disk' 13:tmpfs /dev/shm tmpfs defaults 0 0 14:devpts /dev/pts devpts gid=5,mode=620 0 0
For better result I suggest you pass the –color option to gnu/grep command:
grep -n --color '/dev' /etc/fstab
Sample outputs:
Suggested readings
- For further information and examples see “Linux / UNIX grep Command Tutorial series” or read grep(1) command man page.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.
🐧 0 comments... add one ↓
🐧 0 comments... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |