Using the Linux `grep` command line utility for searching files and inputs
search cancel

Using the Linux `grep` command line utility for searching files and inputs

book

Article ID: 42894

calendar_today

Updated On:

Products

STARTER PACK-7 CA Rapid App Security CA API Gateway

Issue/Introduction

Solution

Background

The grep command is useful for quickly searching files or inputs for strings of text. The syntax of this command is as follows:
grep [OPTIONS] PATTERN [FILE...]

For example, the following command invokes grep with the option "-i (case insensitive)" to search for the string "hostname" in the file "/etc/sysconfig/network"

grep -i hostname /etc/sysconfig/network

Alternatively, the syntax of this command can also specify multiple patterns and multiple files.

grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]

This syntax can be used to search for multiple strings within the same file. For example, the following commands invokes grep to search for all lines that match either "HOSTNAME" or "FORWARDING" in the file "/etc/sysconfig/network"

grep -e HOSTNAME -e FORWARDING /etc/sysconfig/network

Examples

Searching for a single pattern in a file

grep 123 /etc/sysconfig/iptables
[0:0] -A INPUT -i eth0 -p udp -m udp --dport 123 -j ACCEPT
[0:0] -A INPUT -i eth2 -p udp -m udp --dport 123 -j ACCEPT
[0:0] -A INPUT -i eth3 -p udp -m udp --dport 123 -j ACCEPT
[0:0] -A OUTPUT -p udp --dport 123 -j ACCEPT

Overriding case sensitivity

grep -i hostname /etc/sysconfig/network
HOSTNAME=gateway.domain.com

Printing number of matched patterns

grep -c NETWORKING /etc/sysconfig/network
2

Searching multiple files

grep HOSTNAME /etc/sysconfig/network /etc/sysconfig/network-scripts/ifcfg-eth0?
/etc/sysconfig/network:HOSTNAME=gateway.domain.com
/etc/sysconfig/network-scripts/ifcfg-eth0:DHCP_HOSTNAME=gateway

Negative filtering

grep -v "#" /etc/rsyslog.conf?
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$ModLoad imklog
$ModLoad imuxsock

Wildcard pattern matching

grep "server .*org" /etc/ntp.conf
server 0.rhel.pool.ntp.org
server 1.rhel.pool.ntp.org
server 2.rhel.pool.ntp.org

Specifying matching line number

grep -n "server" /etc/ntp.conf?
17:server 0.rhel.pool.ntp.org
18:server 1.rhel.pool.ntp.org
19:server 2.rhel.pool.ntp.org
30:server ? ? ? 127.127.1.0

Cap number of matching patterns

grep -m 2 server /etc/ntp.conf
17:server 0.rhel.pool.ntp.org
18:server 1.rhel.pool.ntp.org
19:server 2.rhel.pool.ntp.org
?

Environment

Release:
Component: APIGTW