How VPS - How to use/setup VPS
  • Home
  • Management guides
    • Web servers software
      • Directadmin
      • Hocvps Script
      • Centmin Mod
      • CWP
      • Kloxo-MR
      • Plesk
    • Control Panels
    • Securing VPS/Servers
      • SSL Certificates
      • Upgrading
      • Authentication
  • Operating System
    • CentOS
    • Fedora
    • Debian
    • Linux
    • Arch
    • BSD
    • CoreOS
  • Reviews
  • Coupon
    • Domain Coupon
    • Hosting Coupon
No Result
View All Result
  • Home
  • Management guides
    • Web servers software
      • Directadmin
      • Hocvps Script
      • Centmin Mod
      • CWP
      • Kloxo-MR
      • Plesk
    • Control Panels
    • Securing VPS/Servers
      • SSL Certificates
      • Upgrading
      • Authentication
  • Operating System
    • CentOS
    • Fedora
    • Debian
    • Linux
    • Arch
    • BSD
    • CoreOS
  • Reviews
  • Coupon
    • Domain Coupon
    • Hosting Coupon
No Result
View All Result
How VPS - How to use/setup VPS
No Result
View All Result
Home Operating System Linux

12 Practical Examples of Linux grep Command

How VPS by How VPS
November 2, 2018
in Linux, Operating System
0
0
SHARES
4
VIEWS
Share on FacebookShare on Twitter

Contents

  1. 1. Search and Find Files
    1. Sample Output
  2. 2. Search and Filter Files
  3. 3. Find all .mp3 Files Only
  4. 4. Display Number of Lines Before or After Search String
  5. 5. Prints Number of Lines Around Match
  6. 6. Count Number of Matches
  7. 7. Search Files by Given String
  8. 8. Search a string Recursively in all Directories
  9. 9. Searches for the entire pattern
  10. 10. Search a string in Gzipped Files
  11. 11. Match Regular Expression in Files
  12. 12. Search a Fixed Pattern String

Have you ever been confronted with the task of looking for a particular string or pattern in a file, yet have no idea where to start looking? Well then, here is grep to the rescue!

12 Practical Examples of Linux grep Command

12 Grep Command Examples

grep is a powerful file pattern searcher that comes equipped on every distribution of Linux. If, for whatever reason, it is not installed on your system, you can easily install it via your package manager (apt-get on Debian/Ubuntu and yum on RHEL/CentOS/Fedora).

$ sudo apt-get install grep         #Debian/Ubuntu
$ sudo yum install grep             #RHEL/CentOS/Fedora

I have found that the easiest way to get your feet wet with grep is to just dive right in and use some real world examples.

1. Search and Find Files

Let’s say that you have just installed a fresh copy of the new Ubuntu on your machine, and that you are going to give Python scripting a shot. You have been scouring the web looking for tutorials, but you see that there are two different versions of Python in use, and you don’t know which one was installed on your system by the Ubuntu installer, or if it installed any modules. Simply run this command:

# dpkg -l | grep -i python
Sample Output
ii  python2.7                        2.7.3-0ubuntu3.4                    Interactive high-level object-oriented language (version 2.7)
ii  python2.7-minimal                2.7.3-0ubuntu3.4                    Minimal subset of the Python language (version 2.7)
ii  python-openssl                   0.12-1ubuntu2.1                     Python wrapper around the OpenSSL library
ii  python-pam                       0.4.2-12.2ubuntu4                   A Python interface to the PAM library

First, we ran dpkg –l, which lists installed *.deb packages on your system. Second, we piped that output to grep –i python, which simple states “go to grep and filter out and return everything with ‘python’ in it.” The –i option is there to ignore-case, as grep is case-sensitive. Using the –i option is a good habit of getting into, unless of course you are trying to nail down a more specific search.

2. Search and Filter Files

The grep can also be used to search and filter within individual files or multiple files. Lets take this scenario:

You are having some trouble with your Apache Web Server, and you have reached out to one of the many awesome forums on the net asking for some help. The kind soul who replies to you has asked you to post the contents of your /etc/apache2/sites-available/default-ssl file. Wouldn’t it be easier for you, the guy helping you, and everyone reading it, if you could remove all of the commented lines? Well you can! Just run this:

# grep –v “#”  /etc/apache2/sites-available/default-ssl

The –v option tells grep to invert its output, meaning that instead of printing matching lines, do the opposite and print all of the lines that don’t match the expression, in this case, the # commented lines.

3. Find all .mp3 Files Only

The grep can be very useful for filtering from stdout. For example, let’s say that you have an entire folder full of music files in a bunch of different formats. You want to find all of the *.mp3 files from the artist JayZ, but you don’t want any of the remixed tracks. Using a find command with a couple of grep pipes will do the trick:

# find . –name “*.mp3” | grep –i JayZ | grep –vi “remix”

In this example, we are using find to print all of the files with a *.mp3 extension, piping it to grep –i to filter out and prints all files with the name “JayZ” and then another pipe to grep –vi which filters out and does not print all filenames with the string (in any case) “remix”.

Suggested Read: 35 Practical Examples of Linux Find Command

4. Display Number of Lines Before or After Search String

Another couple of options are the –A and –B switches, which displays the matched line and number of lines either that come before or after the search string. While the man page gives a more detailed explanation, I find it easiest to remember the options as –A = after, and –B = before:

# ifconfig | grep –A 4 eth0
# ifconfig | grep  -B 2 UP

5. Prints Number of Lines Around Match

The grep’s –C option is similar, but instead of printing the lines that come either before or after the string, it prints the lines in either direction:

# ifconfig | grep –C 2 lo

6. Count Number of Matches

Similar to piping a grep string to word count (wc program) grep’s built-in option can perform the same for you:

# ifconfig | grep –c inet6

7. Search Files by Given String

The –n option for grep is very useful when debugging files during compile errors. It displays the line number in the file of the given search string:

# grep –n “main” setup..py

8. Search a string Recursively in all Directories

If you would like to search for a string in the current directory along with all of the subdirectories, you can specify the –r option to search recursively:

# grep –r “function” *

9. Searches for the entire pattern

Passing the –w option to grep searches for the entire pattern that is in the string. For example, using:

# ifconfig | grep –w “RUNNING”

Will print out the line containing the pattern in quotes. On the other hand, if you try:

# ifconfig | grep –w “RUN”

Nothing will be returned as we are not searching for a pattern, but an entire word.

10. Search a string in Gzipped Files

Deserving some mention are grep’s derivatives. The first is zgrep, which, similar to zcat, is for use on gzipped files. It takes the same options as grep and is used in the same way:

# zgrep –i error /var/log/syslog.2.gz

11. Match Regular Expression in Files

The egrep is another derivative that stands for “Extended Global Regular Expression”. It recognizes additional expression meta-characters such at + ? | and ().

Suggested Read: What’s Difference Between Grep, Egrep and Fgrep in Linux?

egrep is very useful for searching source files, and other pieces of code, should the need arise. It can be invoked from regular grep by specifying the –E option.

# grep –E

12. Search a Fixed Pattern String

The fgrep searches a file or list of files for a fixed pattern string. It is the same as grep –F. A common way of using fgrep is to pass a file of patterns to it:

# fgrep –f file_full_of_patterns.txt file_to_search.txt

This is just a starting point with grep, but as you are probably able to see, it is invaluable for a variety of purposes. Aside from the simple one line commands we have implemented, grep can be used to write powerful cron jobs, and robust shell scripts, for a start.

Suggested Read: 11 ‘Grep’ Commands on Character Classes and Bracket Expressions

Be creative, experiment with the options in the man page, and come up with grep expressions that serve your own purposes!

Source: tecmint.com

Tags: Linux Commandslinux guidelinux vps setup guide
How VPS

How VPS

Related Posts

Failed to download metadata for repo 'appstream' on Centos 8
CentOS

How to fix error: Failed to download metadata for repo ‘appstream’ on Centos 8

February 25, 2022
How to Install Apache Tomcat 8 on CentOS 7
Linux

How to Install Apache Tomcat 8 on CentOS 7?

February 11, 2020
Install Arch Linux With Btrfs Snapshotting
Uncategorized

Install Arch Linux With Btrfs Snapshotting

February 13, 2020
Next Post
How-to Secure your VPS using IPTables

How-to Secure your VPS using IPTables

How-to Setup a Minecraft PE Server on Linux

How-to Setup a Minecraft PE Server on Linux

10 Amazing and Mysterious Uses of (!) Symbol or Operator in Linux Commands

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Follow Us

  • 121 Followers
  • 87.2k Followers

Recommended

How To Install Vagrant On CentOS 6

3 years ago

How to Install Backdrop CMS 1.8.0 on a Debian 9 LAMP VPS

3 years ago

10 Useful Commands to Collect System and Hardware Information in Linux

4 years ago

How To Install LiteSpeed on CentOS

3 years ago

Instagram

    Please install/update and activate JNews Instagram plugin.

Categories

  • Arch
  • Authentication
  • Backups
  • BSD
  • Centmin Mod
  • CentOS
  • Control Panels
  • CoreOS
  • CWP
  • Debian
  • Directadmin
  • Encryption
  • Fedora
  • Firewalls
  • Hocvps Script
  • Hosting providers
  • Kloxo-MR
  • Linux
  • Mitigations
  • Operating System
  • Plesk
  • Reviews
  • Securing VPS/Servers
  • Security Patches
  • SSL Certificates
  • Uncategorized
  • Upgrading
  • VPS/Servers management guides
  • Vulnerability Detection
  • Web servers software
  • Webhosting Control Panel

Topics

Apache Web Server Bluehost Review 2019 Bluehost Review 2020 Bluehost Review 2021 Centmin Mod CentminMod centos install htop fsck htop install HTTP DoS attack Install Snort on an Ubuntu install Zabbix on CentOS install Zabbix on CentOS 7 Linux Commands linux guide linux install htop linux vps setup guide MariaDB MariaDB Error Mysql mysqld error optimize MariaDB optimize Mysql snort Ubuntu
No Result
View All Result

Highlights

Top Free Web Hosting Control Panels To Manage VPS/Dedicated Servers

Webmin Reviews

Virtualmin Reviews

CentOS Web Panel Reviews

Ajenti Reviews

ISPConfig Reviews

Trending

Failed to download metadata for repo 'appstream' on Centos 8
CentOS

How to fix error: Failed to download metadata for repo ‘appstream’ on Centos 8

by How VPS
February 25, 2022
0

I tried to update some extensions by use yum on centOs which I specified in Dockerfile. After...

How to Fix MySQL Error "Plugin 'InnoDB' registration as a STORAGE ENGINE failed"?

How to Fix MySQL Error “Plugin ‘InnoDB’ registration as a STORAGE ENGINE failed”?

November 17, 2020
How to optimize Mysql or MariaDB

How to optimize Mysql or MariaDB

November 3, 2020
Top Free Web Hosting Control Panels To Manage VPS/Dedicated Servers

Top Free Web Hosting Control Panels To Manage VPS/Dedicated Servers

February 17, 2020
Webmin Reviews

Webmin Reviews

February 17, 2020
How VPS – How to use/setup VPS

We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Visit our landing page to see all features & demos.
LEARN MORE »

Recent News

  • How to fix error: Failed to download metadata for repo ‘appstream’ on Centos 8 February 25, 2022
  • How to Fix MySQL Error “Plugin ‘InnoDB’ registration as a STORAGE ENGINE failed”? November 17, 2020
  • How to optimize Mysql or MariaDB November 3, 2020

Categories

  • Arch
  • Authentication
  • Backups
  • BSD
  • Centmin Mod
  • CentOS
  • Control Panels
  • CoreOS
  • CWP
  • Debian
  • Directadmin
  • Encryption
  • Fedora
  • Firewalls
  • Hocvps Script
  • Hosting providers
  • Kloxo-MR
  • Linux
  • Mitigations
  • Operating System
  • Plesk
  • Reviews
  • Securing VPS/Servers
  • Security Patches
  • SSL Certificates
  • Uncategorized
  • Upgrading
  • VPS/Servers management guides
  • Vulnerability Detection
  • Web servers software
  • Webhosting Control Panel

[mc4wp_form]

© 2018 JNews - City News Magazine WordPress theme. All rights belong to their respective owners.
JNews is a top selling 2018 WordPress News, Blog, Newspaper & Magazine Theme.

No Result
View All Result
  • Home

© 2023 JNews - Premium WordPress news & magazine theme by Jegtheme.