{"id":14568,"date":"2023-02-18T13:04:10","date_gmt":"2023-02-18T07:34:10","guid":{"rendered":"https:\/\/www.binarytides.com\/?p=14568"},"modified":"2023-02-18T13:04:10","modified_gmt":"2023-02-18T07:34:10","slug":"grep-command-examples-in-linux","status":"publish","type":"post","link":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/","title":{"rendered":"21+ Grep Command Examples in Linux &#8211; Searching text patterns in files"},"content":{"rendered":"<h3>Grep Command<\/h3>\n<p>Grep command in Linux is primarily used to search files for specific patterns of text, but there is a lot more it can do. The name \u201cgrep\u201d is derived from the command used to perform a similar operation \"ed\" text editor with the operation: g\/re\/p ((globally search for a regular expression and print matching lines).<\/p>\t\t<div class=\"display-ad-unit mobile-wide bsa\" style=\"background:#fff3f3; height:315px;\">\n\n<!-- BinaryTides_S2S_InContent_ROS_Pos1 -->\n<style>\n\t@media only screen and (min-width: 0px) and (min-height: 0px) {\n\t\tdiv[id^=\"bsa-zone_1611170977806-3_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n\t@media only screen and (min-width: 640px) and (min-height: 480px) {\n\t\tdiv[id^=\"bsa-zone_1611170977806-3_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n<\/style>\n<div id=\"bsa-zone_1611170977806-3_123456\"><\/div>\n\n\n<\/div>\n<!-- Time: 0.0016438961029053, Pos: 348, Key: ad_unit_1 -->\n\n\n<p>Now let's get back to the topic of our article: grep.<\/p>\n<h2>Grep Command Examples<\/h2>\n<p>Now lets take at some grep command examples that will show you how to use this powerful commandline tool. Grep is used by everyone including, system administrators to search log files, monitor realtime output from other programs, by developers to search source code files etc.<\/p>\n<p>This is a command that you should definitely get your hands on as an expert.<\/p>\n<p><b>Syntax<\/b><\/p>\n<p>The most basic syntax is as follows.<\/p>\n<pre class=\"pre_text\" >grep [options] PATTERN [FILE...]\r\ngrep [options] [-e PATTERN | -f FILE] [FILE...]<\/pre>\n<h3>1. Simple grep search in a single file<\/h3>\n<p>We will start with a simple grep on a text file:<\/p>\n<pre class=\"terminal\" >$ grep &quot;ListenAddress&quot; \/etc\/ssh\/sshd_config\r\n#ListenAddress 0.0.0.0\r\n#ListenAddress ::<\/pre>\n<p>We see that, in ssh configuration, the ListenAddress is commented out, and we have our first results! We just began the grep journey.<\/p>\n<p><b>Using with cat command<\/b><\/p>\n<p>A very common hack when searching single files, is to combine the use of grep with the cat command like this:<\/p>\n<pre class=\"terminal\" >$ cat \/var\/log\/apache2\/error.log | grep -in down\r\n3:[Thu Feb 16 10:49:49.963444 2023] [mpm_prefork:notice] [pid 811378] AH00170: caught SIGWINCH, shutting down gracefully\r\n$<\/pre>\n<p>First output the contents of a file with cat, then pipe the output to grep. This command is a bit longer, but can often times be easier to remember due to its pipe format. Note the \"-n\" option which prints the line number where the match was found.<\/p>\n<p>The \"-H\" option is used to print the file where the match was found. If you use the -H option when piping the cat output it would report \"stdin input\" like the following:<\/p>\n<pre class=\"terminal\" >$ cat \/var\/log\/apache2\/access.log.1 | grep auth -inH\r\n(standard input):661:auth\r\n(standard input):661:auth\r\n(standard input):662:auth\r\n(standard input):662:auth\r\n(standard input):663:auth\r\n...<\/pre>\n<h3>2. Searching multiple files in directory<\/h3>\n<p>Checking for strings in multiple files. There will be quite some results in the following query so please scroll to see all of them. We will use the \u201c*\u201d symbol for grep to understand we mean expansion:<\/p>\n<pre class=\"terminal\" >$ grep &quot;address&quot; \/etc\/*\r\n&hellip;\r\n\r\ngrep: \/etc\/sudoers.d: Is a directory\r\n\/etc\/sudo_logsrvd.conf:# The hostname or IP address and port to listen on with an optional TLS\r\n\/etc\/sudo_logsrvd.conf:#   listen_address = hostname(tls)\r\n\/etc\/sudo_logsrvd.conf:#   listen_address = hostname:port(tls)\r\n\/etc\/sudo_logsrvd.conf:#   listen_address = IPv4_address(tls)\r\n\/etc\/sudo_logsrvd.conf:#   listen_address = IPv4_address:port(tls)\r\n\/etc\/sudo_logsrvd.conf:#   listen_address = [IPv6_address](tls)\r\n&hellip;\r\ngrep: \/etc\/sysctl.d: Is a directory\r\n&hellip;<\/pre>\n<p>If you note carefully, grep first lists the file in which the match was found, and then prints the line with the matching pattern.<\/p>\t\t<div class=\"display-ad-unit mobile-wide bsa\" style=\"background:#fff3f3; height:315px;\">\n\n\n<!-- BinaryTides_S2S_InContent_ROS_Pos2 -->\n<style>\n\t@media only screen and (min-width: 0px) and (min-height: 0px) {\n\t\tdiv[id^=\"bsa-zone_1611334361252-4_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n\t@media only screen and (min-width: 640px) and (min-height: 480px) {\n\t\tdiv[id^=\"bsa-zone_1611334361252-4_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n<\/style>\n<div id=\"bsa-zone_1611334361252-4_123456\"><\/div>\n\n\n<\/div>\n<!-- Time: 0.0016047954559326, Pos: 3953, Key: ad_unit_2 -->\n\n\n<p>I posted just a snippet, but you noticed some sort of warning already: <\/p>\n<pre class=\"terminal\" >grep: \/etc\/sudoers.d: Is a directory<\/pre>\n<p>The above indicates that we encountered a directory, and we did not search for it. We'll later see how to \u201cfix\u201d this issue.<br \/>\nSometimes, we don\u2019t want to go down in the directory tree and just remain at the current folder depth level: like \/etc\/. <\/p>\n<p><b>Searching the current directory<\/b><\/p>\n<p>Say you are in your home directory and want to search all files. Just use the \"period\" to specify the current directory as the search target for grep.<\/p>\n<pre class=\"terminal\" >$ grep -Ri &#039;search_term&#039; .<\/pre>\n<h3>3. Case insensitive<\/h3>\n<p>This is perhaps the most powerful option to use with grep. By default, grep is case sensitive, but we can make it case insensitive by using the following switch -i:<\/p>\n<p>With the \"-i\" option it will match all cases of the search pattern and would potentially show more matches that it would without the \"-i\" flag.<\/p>\n<pre class=\"terminal\" >$ grep -i &quot;password&quot; \/etc\/ssh\/sshd_config\r\n# To disable tunneled clear text passwords, change to no here!\r\n#PasswordAuthentication yes\r\n#PermitEmptyPasswords no\r\n# Change to yes to enable challenge-response passwords (beware issues with\r\n# PasswordAuthentication. Depending on your PAM configuration,\r\n# the setting of &quot;PermitRootLogin without-password&quot;.\r\n# PAM authentication, then enable this but set PasswordAuthentication\r\nPasswordAuthentication yes<\/pre>\n<p>Now let\u2019s compare this with the following:<\/p>\n<pre class=\"terminal\" >$ grep &quot;password&quot; \/etc\/ssh\/sshd_config\r\n# To disable tunneled clear text passwords, change to no here!\r\n# Change to yes to enable challenge-response passwords (beware issues with\r\n# the setting of &quot;PermitRootLogin without-password&quot;.<\/pre>\n<p>The difference can be seen easily. Another point to remember is that there is some speed tradeoff between case-sensitive and insensitive searches. <\/p>\n<p>For large volumes of search text\/files, a case-insensitive search will be slower since there will be some lowercase\/uppercase transforms and potentially other factors. To what degree it is slower and when it deserves an article on its own.<\/p>\n<h3>4. Grouping switches<\/h3>\n<p>If you just want to print the matched text and not the whole line\/sentence where it was found, then use the \"-o\" option. It was just print the matching text without the rest of the line and each match will be printed on a newline to keep it distinct.<\/p>\n<pre class=\"terminal\" >$ grep -io &quot;yes&quot; \/etc\/ssh\/sshd_config \\ \r\n\/etc\/lvm\/lvm.conf\r\n\/etc\/ssh\/sshd_config:yes\r\n\/etc\/ssh\/sshd_config:yes\r\n&hellip;\r\n\/etc\/lvm\/lvm.conf:yes<\/pre>\n<p>You also see in the example how multiple files can be added to the search list just by providing them as additional parameters to the command. We also used the \u201c\\\u201d backslash bash operator, which means that the command continues on the next line. It will be executed when you press enter and there is no \u201c\\\u201d on the current line you are writing.<\/p>\t\t<div class=\"display-ad-unit mobile-wide bsa\" style=\"background:#fff3f3; height:315px;\">\n<!-- BinaryTides_S2S_InContent_ROS_Pos3 -->\n<style>\n\t@media only screen and (min-width: 0px) and (min-height: 0px) {\n\t\tdiv[id^=\"bsa-zone_1672330111515-1_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n\t@media only screen and (min-width: 640px) and (min-height: 480px) {\n\t\tdiv[id^=\"bsa-zone_1672330111515-1_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n<\/style>\n<div id=\"bsa-zone_1672330111515-1_123456\"><\/div>\n<\/div>\n<!-- Time: 0.0017340183258057, Pos: 7656, Key: ad_unit_3 -->\n\n\n<p>The above example in real life scenario becomes:<\/p>\n<pre class=\"terminal\" >$ grep &quot;yes&quot; \/etc\/ssh\/sshd_config \/etc\/lvm\/lvm.conf\r\n\/etc\/ssh\/sshd_config:PermitRootLogin yes\r\n\/etc\/ssh\/sshd_config:#StrictModes yes\r\n\/etc\/ssh\/sshd_config:#PubkeyAuthentication yes\r\n\/etc\/ssh\/sshd_config:# Change to yes if you don&#039;t trust ~\/.ssh\/known_hosts for\r\n\/etc\/ssh\/sshd_config:#IgnoreRhosts yes\r\n\/etc\/ssh\/sshd_config:#PasswordAuthentication yes\r\n\/etc\/ssh\/sshd_config:# Change to yes to enable challenge-response passwords (beware issues with\r\n\/etc\/ssh\/sshd_config:#KerberosOrLocalPasswd yes\r\n\/etc\/ssh\/sshd_config:#KerberosTicketCleanup yes\r\n\/etc\/ssh\/sshd_config:#GSSAPICleanupCredentials yes\r\n\/etc\/ssh\/sshd_config:#GSSAPIStrictAcceptorCheck yes\r\n\/etc\/ssh\/sshd_config:# Set this to &#039;yes&#039; to enable PAM authentication, account processing,\r\n\/etc\/ssh\/sshd_config:UsePAM yes\r\n\/etc\/ssh\/sshd_config:#AllowAgentForwarding yes\r\n\/etc\/ssh\/sshd_config:#AllowTcpForwarding yes\r\n\/etc\/ssh\/sshd_config:X11Forwarding yes\r\n\/etc\/ssh\/sshd_config:#X11UseLocalhost yes\r\n\/etc\/ssh\/sshd_config:#PermitTTY yes\r\n\/etc\/ssh\/sshd_config:#PrintLastLog yes\r\n\/etc\/ssh\/sshd_config:#TCPKeepAlive yes\r\n\/etc\/ssh\/sshd_config:PasswordAuthentication yes\r\n\/etc\/lvm\/lvm.conf:      # Any &#039;yes&#039; or &#039;no&#039; questions not overridden by other arguments are<\/pre>\n<h3>5. Search in binary files<\/h3>\n<p>Grep is designed to work with text, but if needed it can also process binary files with the use of \"-a\" option. We will also use the \u201co\u201d switch to print only matching text, useful in not seeing many non-printable characters displayed in results:<\/p>\n<pre class=\"terminal\" >root@ubu:~\/work# grep -ao &quot;LANGUAGE=&quot; \/bin\/passwd\r\nLANGUAGE=<\/pre>\n<p>Or to see the whole \"line\" we would use the following. This particular example is not very useful but it's just meant for exercising purposes:<\/p>\n<pre class=\"terminal\" >root@ubu:~\/work# grep -a &quot;LANGUAGE=&quot; \/bin\/passwd\r\ncan&#039;t setuid(0)FORCE_SHADOWyes\/var\/lib\/extrausers\/shadowCHFN_AUTHCHSH_AUTHCRACKLIB_DICTPATHENV_HZENVIRON_FILEENV_TZFAILLOG_ENABISSUE_FILELASTLOG_ENABLOGIN_STRINGMAIL_CHECK_ENABMOTD_FILENOLOGINS_FILEOBSCURE_CHECKS_ENABPASS_ALWAYS_WARNPASS_CHANGE_TRIESPASS_MAX_LENPASS_MIN_LENPORTTIME_CHECKS_ENABQUOTAS_ENABSU_WHEEL_ONLYULIMITCHFN_RESTRICTCONSOLE_GROUPSCONSOLECREATE_HOMEDEFAULT_HOMEENCRYPT_METHODENV_PATHENV_SUPATHERASECHARFAKE_SHELLFTMP_FILEHOME_MODEHUSHLOGIN_FILEKILLCHARLASTLOG_UID_MAXLOGIN_RETRIESLOGIN_TIMEOUTLOG_OK_LOGINSLOG_UNKFAIL_ENABMAIL_DIRMAIL_FILEMAX_MEMBERS_PER_GROUPMD5_CRYPT_ENABPASS_MAX_DAYSPASS_MIN_DAYSPASS_WARN_AGESHA_CRYPT_MAX_ROUNDSSHA_CRYPT_MIN_ROUNDSSUB_GID_COUNTSUB_GID_MAXSUB_GID_MINSUB_UID_COUNTSUB_UID_MAXSUB_UID_MINSULOG_FILESU_NAMESYS_GID_MAXSYS_GID_MINSYS_UID_MAXSYS_UID_MINTTYGROUPTTYPERMTTYTYPE_FILEUMASKUSERDEL_CMDUSERGROUPS_ENABSYSLOG_SG_ENABSYSLOG_SU_ENABLANG=LANGUAGE=LC__RLD_=BASH_ENV=HOME=IFS=KRB_CONF=LD_LIBPATH=MAIL=NLSPATH=SHELL=SHLIB_PATH=alldeleteexpirehelpinactivekeep-tokensmindaysquietrepositorystatusunlockwarndaysmaxdaysP\r\n&hellip;<\/pre>\t\t<div class=\"display-ad-unit mobile-wide bsa\" style=\"background:#fff3f3; height:315px;\">\n\n<!-- BinaryTides_S2S_InContent_ROS_Pos4 -->\n<style>\n\t@media only screen and (min-width: 0px) and (min-height: 0px) {\n\t\tdiv[id^=\"bsa-zone_1672740659643-7_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n\t@media only screen and (min-width: 640px) and (min-height: 480px) {\n\t\tdiv[id^=\"bsa-zone_1672740659643-7_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n<\/style>\n<div id=\"bsa-zone_1672740659643-7_123456\"><\/div>\n\n<\/div>\n<!-- Time: 0.0018820762634277, Pos: 11311, Key: ad_unit_4 -->\n\n\n<h3>6. Recursive grep - Search sub-directories as well<\/h3>\n<p>For searching all sub-directories under a given path, we can use the -R switch (can be capital or lowercase, the difference is that capital follows symlinks), which means searching recursively. <\/p>\n<p>The following command will search the current directory recursively for files containing a term.<\/p>\n<pre class=\"terminal\" >$ grep -Ri &#039;config&#039; .<\/pre>\n<p>The recursive option will go as deep as possible when looking for sub-directories.<\/p>\n<h3>7. Output with Context<\/h3>\n<p>Sometimes we need to see the context of a matching text, which is the text preceding or following the match containing line. For this, we have the A,B,C triad of switches, which are namely After, Before and Context switches. They should be followed by a number that prints the number of lines in the context. <\/p>\n<p>Lets take an example. The following search will search all files under \/etc\/ssh directory recursively, search in binary files also and for each find will display 1 line before and 1 line after: the C context:<\/p>\n<pre class=\"terminal\" >$ grep -Ra -C1 &quot;yes&quot; \/etc\/* | head\r\n\/etc\/adduser.conf-\r\n\/etc\/adduser.conf:# If GROUPHOMES is &quot;yes&quot;, then the home directories will be created as\r\n\/etc\/adduser.conf-# \/home\/groupname\/user.\r\n--\r\n\/etc\/adduser.conf-\r\n\/etc\/adduser.conf:# If LETTERHOMES is &quot;yes&quot;, then the created home directories will have\r\n\/etc\/adduser.conf-# an extra directory - the first letter of the user name. For example:\r\n--\r\n\/etc\/adduser.conf-\r\n\/etc\/adduser.conf:# The USERGROUPS variable can be either &quot;yes&quot; or &quot;no&quot;.  If &quot;yes&quot; each<\/pre>\n<p>Nice results. We also used the head command, which without any parameters, displays only the first 10 lines of the result. Otherwise, we would have been spammed with tons of text. We\u2019ll soon learn how to gain more control with grep to see only what we are interested in. We started to see the context, but just remember chapter 4: we wanted to see the full line for the match:<\/p>\n<pre class=\"terminal\" >$ grep -Ra -C0 &quot;yes&quot; \/etc\/* | head\r\n\/etc\/adduser.conf:# If GROUPHOMES is &quot;yes&quot;, then the home directories will be created as\r\n--\r\n\/etc\/adduser.conf:# If LETTERHOMES is &quot;yes&quot;, then the created home directories will have\r\n--\r\n\/etc\/adduser.conf:# The USERGROUPS variable can be either &quot;yes&quot; or &quot;no&quot;.  If &quot;yes&quot; each\r\n--\r\n\/etc\/adduser.conf:USERGROUPS=yes\r\n--\r\n\/etc\/adduser.conf:# If SETGID_HOME is &quot;yes&quot; home directories for users with their own\r\n--<\/pre>\n<p>The command can be also compacted as: <\/p>\n<pre class=\"terminal\" >$ grep -RaC0 &ldquo;yes&rdquo; \/etc\/*<\/pre>\n<p>Just be careful with command switches order, for example the following won\u2019t work: grep -RC0a!<\/p>\n<p>The \"-B\" option will print those lines before the matching text line and the \"-A\" option will print those lines after the matching text line. Its that simple!<\/p>\t\t<div class=\"display-ad-unit mobile-wide bsa\" style=\"background:#fff3f3; height:315px;\">\n\n<!-- BinaryTides_S2S_InContent_ROS_Pos5 -->\n<style>\n\t@media only screen and (min-width: 0px) and (min-height: 0px) {\n\t\tdiv[id^=\"bsa-zone_1672740746864-5_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n\t@media only screen and (min-width: 640px) and (min-height: 480px) {\n\t\tdiv[id^=\"bsa-zone_1672740746864-5_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n<\/style>\n<div id=\"bsa-zone_1672740746864-5_123456\"><\/div>\n\n<\/div>\n<!-- Time: 0.0019850730895996, Pos: 14900, Key: ad_unit_5 -->\n\n\n<h3>8. Colorful Output<\/h3>\n<p>Another basic command would be to colorize the output. We will check the kernel ring buffer for keyword info, shorthand for information. Very useful is also to check it for warnings or errors:<\/p>\n<pre class=\"terminal\" >$ dmesg | grep -i &quot;info&quot; --color=auto\r\n[    0.011533] ACPI: Using ACPI (MADT) for SMP configuration information<\/pre>\n<p>Most modern Linux distributions already display grep output with colors, because they have setup an alias for the grep command with the --color option. You can check this by running the alias command as follows and see how your system is configured.<\/p>\n<pre class=\"terminal\" >$ alias\r\nalias egrep=&#039;egrep --color=auto&#039;\r\nalias fgrep=&#039;fgrep --color=auto&#039;\r\nalias grep=&#039;grep --color=auto&#039;\r\nalias l=&#039;ls -CF&#039;\r\nalias la=&#039;ls -A&#039;\r\nalias ll=&#039;ls -alF&#039;\r\nalias ls=&#039;ls --color=auto&#039;<\/pre>\n<p>The above output indicates that the switch to colorize the output is always appended to the command.<\/p>\n<h3>9. Words with sub-strings<\/h3>\n<p>We can also use grep to search for full words containing a specific substring with the \"-w\" switch. It will select only those lines containing matches that form whole words. <\/p>\n<pre class=\"terminal\" ># this will match error everywhere\r\n$ grep -i &quot;error&quot; \/var\/log\/syslog\r\n\r\n# this will match the error in: &#039;SSL error code 1&#039; but not &#039;net_error&#039;\r\n$ grep -wi &quot;error&quot; \/var\/log\/syslog<\/pre>\n<h3>10. Match inversion - Exclude some entries<\/h3>\n<p>The \"-v\" switch can be used to exclude specific entries that match a given pattern. <\/p>\n<p>When we grep something in process list, we always see the grep command itself as well. We can exclude it with a second grep command and \"-v\" option.<\/p>\n<pre class=\"terminal\" >$ ps aux | grep bash | grep -v grep\r\ndragos     36272  0.0  0.1   8732  5292 pts\/0    Ss   Feb05   0:00 -bash<\/pre>\n<p>Lets say you want to display all lines in a file except those that contain a # (which indicates a comment line). Lets scan the \/etc\/fstab file and see non-comment lines.<\/p>\n<pre class=\"terminal\" >$ cat \/etc\/fstab | grep -v &#039;#&#039;\r\nUUID=19d84ceb-8046-4f8d-a85a-cda49515d92c \/               ext4    errors=remount-ro 0       1\r\n\r\n\r\n\r\n\r\nUUID=0cc9c458-380f-4600-bc10-afd062c8ae1f none swap sw 0 0\r\n\r\n$<\/pre>\n<h3>11. Counting matches<\/h3>\n<p>The \"-c\" flag will display the count of matches found in each file encountered. This can be useful in some situations like when reading log files.<\/p>\n<pre class=\"terminal\" >$ grep -Rc &quot;error&quot; \/var\/log\/*\r\n&hellip;\r\n\/var\/log\/dpkg.log.1:23\r\n&hellip;\r\n\/var\/log\/syslog:1\r\n\/var\/log\/syslog.1:13\r\n\/var\/log\/syslog.2.gz:0\r\n\/var\/log\/syslog.3.gz:0\r\n\/var\/log\/syslog.4.gz:0\r\n\/var\/log\/ubuntu-advantage.log:0\r\n\/var\/log\/ubuntu-advantage-timer.log:0\r\n\/var\/log\/ubuntu-advantage-timer.log.1:0\r\n\/var\/log\/unattended-upgrades\/unattended-upgrades-dpkg.log.1.gz:0\r\n&hellip;<\/pre>\n<h3>12. Stop after N matches<\/h3>\n<p>But we might want to stop after a certain number of results, if we only want the first x occurrences.<br \/>\nStop after n results<br \/>\nDisplay only first x matches: with m :<\/p>\n<pre class=\"terminal\" >$ grep -m1 &quot;password&quot; \/etc\/ssh\/sshd_config\r\n# To disable tunneled clear text passwords, change to no here!<\/pre>\n<h3>12. Line numbering<\/h3>\n<p>The \"-n\" option will instruct grep to show the line number in the file where the match was found. This can be really powerful if you want to find and then edit something in vi or nano.<\/p>\n<pre class=\"terminal\" >$ grep -n &quot;error&quot; \/var\/log\/syslog\r\n1147:Feb 11 10:18:16 ubu root: The installation has errored. Please check.<\/pre>\n<h3>14. Useful output switches<\/h3>\n<p>Sometimes we need to have the output of grep saved to a file. For this, we will be needing the following switches:<\/p>\n<p>-b print the byte offset of the match within the input file<br \/>\n-H print the filename containing a match<br \/>\n-h do not print the filename containing a match<br \/>\n-n print the line number of each match<br \/>\n-T print an initial Tab before matches so that output is aligned<\/p>\n<p>Example: case insensitive search with line numbers:<\/p>\n<pre class=\"terminal\" >$ grep -in &quot;^Feb.*enp0.*left.*&quot; \/var\/log\/syslog\r\n1155:Feb 11 10:32:00 ubu kernel: [927982.483352] device enp0s3 left promiscuous mode\r\n&hellip;<\/pre>\n<h3>15. Regular expressions<\/h3>\n<p>Now that we know the basics, let's match with regular expressions. This is a powerful feature, and if used properly can spare you a lot of time searching for text in files and logs. With regular expressions you can search for and filter nearly any kind of text pattern provided it can be expressed using regex syntax.<\/p>\n<p>The regex format supported by grep use the following characters with specific meanings:<\/p>\n<pre class=\"pre_text\" >&lsquo;^&rsquo; and &lsquo;$&rsquo; at the beginning of the pattern anchors the pattern to the start of the line\r\n&lsquo;$&rsquo; anchors the pattern to the end of the line\r\n&lsquo;.&rsquo; will match any character\r\n? The preceding item is optional and matched at most once\r\n* The preceding item will be matched zero or more times\r\n+ The preceding item will be matched one or more times\r\n{n} The preceding item is matched exactly n times\r\n{n,} The preceding item is matched n or more times\r\n{,m} The preceding item is matched at most m times\r\n{n,m} The preceding item is matched at least n times, but not more than m times\r\nescaped characters: any special character can be matched as a regular character by escaping it with a &lsquo;\\&rsquo;\r\n\\b in a regular expression means &quot;word boundary&quot;; this anchor signifies beginning or end of the word\r\ncharacter range: a set of characters enclosed in a &lsquo;[&lsquo; and &lsquo;]&rsquo; square brackets specify a range of characters\r\n-E extended regular expression, almost everything in this group\r\n[:alpha:]\tany lower and upper case letter\r\n[:digit:]\t            any number.\r\n[:alnum:]\tany lower and upper case letter or digit\r\n[:space:]\tany whites&shy;pace<\/pre>\n<p>The following options control the format of regular expressions that we can feed into grep.<\/p>\n<pre class=\"pre_text\" >Patterns options:\r\n-F, --fixed-strings   # list of fixed strings\r\n-G, --basic-regexp    # basic regular expression (default)\r\n-E, --extended-regexp # extended regular expression\r\n-P, --perl-regexp     # perl compatible regular expression<\/pre>\n<p>The following example will find all IP addresses on all interfaces on the system:<\/p>\n<pre class=\"terminal\" >$ ip address | grep -oE &quot;\\b([0-9]{1,3}\\.){3}[0-9]{1,3}\\b&quot;\r\n127.0.0.1\r\n192.168.1.25\r\n192.168.1.255\r\n172.18.0.1\r\n172.18.255.255\r\n172.17.0.1\r\n172.17.255.255<\/pre>\n<p>And another more complex example: find all IP addresses under \/etc\/ directory, only one match per file:<\/p>\n<pre class=\"terminal\" >$ grep -oERa -m1 &quot;\\b([0-9]{1,3}\\.){3}[0-9]{1,3}\\b&quot; \/etc\/*\r\n\/etc\/alternatives\/netcat:0.0.0.0\r\n\/etc\/alternatives\/rlogin:127.0.0.1\r\n&hellip;&hellip;&hellip;\r\n\/etc\/systemd\/resolved.conf:1.1.1.1\r\n\/etc\/systemd\/resolved.conf:1.0.0.1<\/pre>\n<h3>16. Grepping multiple patterns<\/h3>\n<p>Grep can also search for multiple different patterns in a single command. Just concatenate the patterns with a \"\\|\" character. Note that its a \"|\" character that is escaped using backslash.<\/p>\n<pre class=\"terminal\" >$ grep &#039;error\\|warning&#039; \/var\/log\/syslog\r\nAn error occurred with..\r\n&hellip;\r\nWarning: The following configuration file is deprecated:..<\/pre>\n<p>What is the difference between -e and -E switches ?<br \/>\n-e switch for indicating pattern<br \/>\n-E controls whether you need to escape certain special characters<\/p>\n<p>man grep explains -E in more details:<\/p>\n<pre class=\"pre_text\" >Basic vs Extended Regular Expressions\r\nIn basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their \r\nspecial meaning; instead use the backslashed versions \\?, \\+, \\{, \\|, \\(, and \\).\r\n\r\nTraditional  egrep  did  not  support  the  {  meta-character, and some egrep \r\nimplementations support \\{ instead, so portable scripts should avoid { in grep -E\r\npatterns and should use [{] to match a literal {.\r\n\r\nGNU grep -E attempts to support traditional usage by assuming that { is not \r\nspecial if it would be the start of an invalid interval specification. \r\nFor example, the command grep -E &#039;{1&#039; searches for the two-character string {1 \r\ninstead of reporting a syntax error in the regular expression.  POSIX.2 allows \r\nthis behavior as an extension, but portable scripts should avoid it.<\/pre>\n<p>A real life example. We will be searching for error keyword or warning in the syslog files:<\/p>\n<pre class=\"terminal\" >$ grep -i &#039;error\\|warning&#039; \/var\/log\/syslog*\r\n\/var\/log\/syslog:Feb 11 10:18:16 ubu root: The installation has errored. Please check.\r\n&hellip;\r\n\/var\/log\/syslog.1:Jan 31 14:02:52 ubu networkd-dispatcher[766]: WARNING:Unknown index 4 seen, reloading interface list\r\n\/var\/log\/syslog.1:Jan 31 14:03:19 ubu networkd-dispatcher[766]: WARNING:Unknown index 5 seen, reloading interface list\r\n\/var\/log\/syslog.1:Jan 31 14:03:20 ubu networkd-dispatcher[766]: WARNING:Unknown index 6 seen, reloading interface list<\/pre>\n<p>We will see soon, at the end of the article, how this example can be improved!<\/p>\n<h3>17. Use search patterns from a file <\/h3>\n<p>The \"-f\" option can be used to specify a file containing a list of patterns one in each line. This allows us to search for lots of patterns in one go, without having to specify a long list on the command line itself.<\/p>\n<pre class=\"terminal\" >$ grep -f pattern_file content_file | head\r\nxyz\r\ndarboard\r\n012\r\ngang\r\ntt<\/pre>\n<p>Here are the contents of the files.<\/p>\n<pre class=\"terminal\" >$ cat pattern_file\r\n[abc]\r\n[def]\r\n[0-9]\r\n[a-z]\r\n\r\n$ cat content_file\r\nxyz\r\ndarboard\r\n012\r\ngang\r\ntt<\/pre>\n<h3>18. Literal matching<\/h3>\n<p>Another more advanced usage of grep is using the \"-F\" switch, which is different from \"-f\". The \"-F\" option will determine patterns to match literally - no regex interpretation will be done on the pattern(s):<\/p>\n<pre class=\"terminal\" >$ grep -F $&#039;conf&#039; &lt;&lt;&lt; $&#039;\\n\/etc\/ssh\/\\nconf&#039;\r\nconf<\/pre>\n<p>Here we used the $ following by a quoted string. More information can be found on <a href=\"https:\/\/www.gnu.org\/software\/bash\/manual\/html_node\/ANSI_002dC-Quoting.html\">this page<\/a>.<\/p>\n<pre class=\"quote\">\r\nWords of the form $&#039;string&#039; are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.\r\n<\/pre>\n<p>Basically, we wanted the escape character \\n to be replaced by its ANSI code and then we instructed grep to search in that string for the occurrences of conf(conf usually is a prefix of configuration files). Also of importance is the fact that \u2018-F\u2019 involves not using regex which speeds up the search for large files.<\/p>\n<h3>19. Piping<\/h3>\n<p>We sometimes want to parse the output of another command with grep, and this is called piping, please see the following example:<\/p>\n<pre class=\"terminal\" >$ sudo dmesg | grep -i error\r\n[    4.962448] [drm:vmw_host_printf [vmwgfx]] *ERROR* Failed to send host log message.<\/pre>\n<p>Where the output of the kernel ring buffer was piped - sent - to grep as input, then we searched for error messages and we found one. Sudo was used because a regular user cannot access the kernel ring buffer without it.<\/p>\n<p>And the promised example from chapter 9. We finally made it to more cadvanced examples, something Linux sysadmins need frequently like seeing enabled parameters in configuration files:<\/p>\n<pre class=\"terminal\" >$ grep -v &quot;#&quot; \/etc\/ssh\/sshd_config | grep -E &quot;\\s&quot;\r\nInclude \/etc\/ssh\/sshd_config.d\/*.conf\r\nPermitRootLogin yes\r\nKbdInteractiveAuthentication no\r\nUsePAM yes\r\nX11Forwarding yes\r\nPrintMotd no\r\nAcceptEnv LANG LC_*\r\nSubsystem sftp  \/usr\/lib\/openssh\/sftp-server\r\nPasswordAuthentication yes<\/pre>\n<p>Please pay attention: the following example will not produce the same results as before:<\/p>\n<pre class=\"terminal\" >$ grep -v &quot;#&quot; -E &ldquo;\\s&rdquo; \/etc\/ssh\/sshd_config<\/pre>\n<p>It will produce results but not the same one because here the E switch will enable extended grep features and \u201c#\u201d will be treated differently, not as literal \u201c#\u201d.<\/p>\n<h3>20. Suppressing error messages<\/h3>\n<p>Grep sometimes(if used incorrectly mostly) yields errors and in such scenarios it's useful to make it quiet with:<br \/>\n-s or \u2013no-messages switches. In the example below we will get a lot of permission denied errors that we can suppres with -s:<\/p>\n<pre class=\"terminal\" >$ grep -ER &quot;=*yes&quot; \/etc\/*\r\n\/etc\/systemd\/journald.conf:#ReadKMsg=yes\r\n\/etc\/systemd\/system.conf:#LogColor=yes\r\n\/etc\/systemd\/system.conf:#DumpCore=yes\r\n\/etc\/systemd\/system.conf:#ShowStatus=yes\r\n\/etc\/systemd\/system.conf:#DefaultMemoryAccounting=yes\r\n\/etc\/ufw\/ufw.conf:# Set to yes to start on boot. If setting this remotely, be sure to add a rule\r\n\/etc\/usb_modeswitch.conf:# To enable an option, set it to &quot;1&quot;, &quot;yes&quot; or &quot;true&quot; (case doesn&#039;t matter)\r\n&hellip;<\/pre>\n<p>Suppressed errors results:<\/p>\n<pre class=\"terminal\" >$ grep -sRE &quot;=*yes&quot; \/etc\/* | tail\r\n\/etc\/systemd\/journald.conf:#ReadKMsg=yes\r\n\/etc\/systemd\/system.conf:#LogColor=yes\r\n\/etc\/systemd\/system.conf:#DumpCore=yes\r\n\/etc\/systemd\/system.conf:#ShowStatus=yes\r\n\/etc\/systemd\/system.conf:#DefaultMemoryAccounting=yes\r\n\/etc\/systemd\/system.conf:#DefaultTasksAccounting=yes\r\n\/etc\/ufw\/ufw.conf:# Set to yes to start on boot. If setting this remotely, be sure to add a rule\r\n\/etc\/usb_modeswitch.conf:# To enable an option, set it to &quot;1&quot;, &quot;yes&quot; or &quot;true&quot; (case doesn&#039;t matter)\r\n&hellip;<\/pre>\n<p>Above we search recursively in the \/etc\/ directory for files of which lines have = yes in their configuration.<\/p>\n<p>Let\u2019s make this more useful. Let\u2019s search for yes configuration lines followed by space any number of times and suppres errors at the same time, and only show the end of the results (for not spamming the terminal, in a real case scenario you would want it without tail or sent to a file):<\/p>\n<pre class=\"terminal\" >$ grep -sRE &quot;=[[:space:]]+yes&quot; \/etc\/* | tail\r\n\/etc\/samba\/smb.conf:   pam password change = yes\r\n\/etc\/samba\/smb.conf:   usershare allow guests = yes\r\n\/etc\/samba\/smb.conf:;   read only = yes\r\n\/etc\/samba\/smb.conf:;   guest ok = yes\r\n\/etc\/samba\/smb.conf:;   read only = yes\r\n\/etc\/skel\/.bashrc:if [ &quot;$color_prompt&quot; = yes ]; then\r\n\/etc\/sos\/sos.conf:#verify = yes\r\n\/etc\/sos\/sos.conf:#batch = yes\r\n\/etc\/ssl\/openssl.cnf:ordering           = yes   # Is ordering defined for timestamps?\r\n\/etc\/ssl\/openssl.cnf:tsa_name           = yes   # Must the TSA name be included in the reply?<\/pre>\n<p>yes and no:<\/p>\n<pre class=\"terminal\" >$ grep -sRE &quot;=[[:space:]]+yes|=[[:space:]]+no&quot; \/etc\/* | tail\r\n\/etc\/ssl\/openssl.cnf:preserve   = no                    # keep passed DN ordering\r\n\/etc\/ssl\/openssl.cnf:# keyUsage = nonRepudiation, digitalSignature, keyEncipherment\r\n\/etc\/ssl\/openssl.cnf:keyUsage = nonRepudiation, digitalSignature, keyEncipherment\r\n\/etc\/ssl\/openssl.cnf:# keyUsage = nonRepudiation, digitalSignature, keyEncipherment\r\n\/etc\/ssl\/openssl.cnf:ordering           = yes   # Is ordering defined for timestamps?\r\n\/etc\/ssl\/openssl.cnf:tsa_name           = yes   # Must the TSA name be included in the reply?\r\n\/etc\/ssl\/openssl.cnf:ess_cert_id_chain  = no    # Must the ESS cert id chain be included?\r\n\/etc\/sudo_logsrvd.conf:#accept_priority = notice<\/pre>\n<h3>21. Other useful switches<\/h3>\n<p>Another useful switches that are worth looking into are:<br \/>\n  -x, --line-regexp         force PATTERN to match only whole lines<br \/>\n  -z, --null-data           a data line ends in 0 byte, not newline<\/p>\n<p>A more complete command switch for you to have is:<br \/>\ngrep -HhrilLnqvsoweFEABCz PATTERN FILE<\/p>\n<p>Think of it more like a cheat sheet or a mnemonic. <\/p>\n<p>Congratulations, you reached almost the end of the article, lets see some more real life examples, using everything we\u2019ve learned:<\/p>\n<p>Seeing all enabled parameters in a configuration file that is using \u201c#\u201d as a line comment:<\/p>\n<pre class=\"terminal\" >$ grep -v &quot;#&quot; \/etc\/ssh\/sshd_config | grep -E &quot;\\s&quot;\r\nInclude \/etc\/ssh\/sshd_config.d\/*.conf\r\nPermitRootLogin yes\r\nKbdInteractiveAuthentication no\r\nUsePAM yes\r\nX11Forwarding yes\r\nPrintMotd no\r\nAcceptEnv LANG LC_*\r\nSubsystem sftp  \/usr\/lib\/openssh\/sftp-server\r\nPasswordAuthentication yes<\/pre>\n<p>Find errors in all files changed in the last 24 hours under \/var\/log directory recursively, and print the matching line. Also scroll the text with more command - this command allows you to scroll at own pace in results with keyboard:<\/p>\n<pre class=\"terminal\" >find \/var\/log\/ -name &#039;*&#039; -exec grep -H &quot;error&quot; {} \\;<\/pre>\n<p>Searching for a number in square brackets:<br \/>\nSuppose we want to search for \u201c[50]\u201d<\/p>\n<pre class=\"terminal\" >$ echo &quot;[50]&quot; | grep &#039;\\[[^]]*50[^]]*]&#039;\r\n[50]\r\nWhat we just did:\r\n\\[: matches a [\r\n[^]]*: matches 0 or of any characters that are not ]\r\n50: maatches text 50\r\n[^]]*: Match 0 or of any characters that are not ]\r\n]: Match a ]<\/pre>\n<p>Find lines not containing pattern. A variation of a previous example:<\/p>\n<pre class=\"terminal\" >$ grep -vE &quot;^#&quot; \/etc\/ssh\/sshd_config | grep &quot;[[:space:]]&quot;\r\nInclude \/etc\/ssh\/sshd_config.d\/*.conf\r\nPermitRootLogin yes\r\nKbdInteractiveAuthentication no\r\nUsePAM yes\r\nX11Forwarding yes\r\nPrintMotd no\r\nAcceptEnv LANG LC_*\r\nSubsystem sftp  \/usr\/lib\/openssh\/sftp-server\r\nPasswordAuthentication yes<\/pre>\n<p>Set how many lines to show before (-B) and after (-A) pattern:<\/p>\n<pre class=\"terminal\" >root@ubu:~\/work# grep -B 3 -A 2 &quot;.*err&quot; \/var\/log\/syslog\r\nFeb 11 09:17:01 ubu CRON[67703]: (root) CMD (   cd \/ &amp;amp;&amp;amp; run-parts --report \/etc\/cron.hourly)\r\nFeb 11 10:17:01 ubu CRON[67993]: (root) CMD (   cd \/ &amp;amp;&amp;amp; run-parts --report \/etc\/cron.hourly)\r\nFeb 11 10:17:20 ubu root: Error 1\r\nFeb 11 10:18:16 ubu root: The installation has errored. Please check.\r\nFeb 11 10:31:59 ubu kernel: [927981.373038] Bluetooth: Core ver 2.22\r\nFeb 11 10:31:59 ubu kernel: [927981.373186] NET: Registered PF_BLUETOOTH protocol family<\/pre>\n<p>Find all files that match  in <\/p>\n<pre class=\"terminal\" >$ grep -rnw \/var\/log\/ -e &quot;.*\\.h$&quot; | tail\r\n&hellip;\r\n\/usr\/share\/man\/man7\/openssl-core.h.7ssl.gz\r\n\/usr\/share\/man\/man7\/openssl-core_dispatch.h.7ssl.gz\r\n\/var\/log\/aide\/aide.log:101232:File: \/usr\/share\/man\/man7\/openssl-core_names.h.7ssl.gz<\/pre>\n<p>Variation of excluding grep from the output of ps: surround first letter of desired search result with \u201c[]\u201d: <\/p>\n<pre class=\"terminal\" ># ps aux | grep &#039;[b]ash&#039;\r\ndragos     36272  0.0  0.1   8996  4644 pts\/0    Ss   Feb05   0:00 -bash\r\nroot       61324  0.0  0.1   9052  5496 pts\/1    S    Feb09   0:00 -bash\r\nroot       64699  0.0  0.1   9052  5676 pts\/4    Ss   Feb10   0:00 -bash\r\nroot       67421  0.0  0.1   9292  5952 pts\/2    Ss   07:19   0:02 -bash\r\n[term]\r\n\r\nColorization of search pattern only, in results, and display all other results: nginx will appear colorized:\r\n\r\n[term]\r\n$ ps aux | grep -E --color &#039;nginx|$&#039;\r\n&hellip;\r\nroot       70233  0.0  0.0  10068  1568 pts\/2    R+   17:19   0:00 ps aux\r\nroot       70234  0.0  0.0   6608  2288 pts\/2    S+   17:19   0:00 grep --color=auto -E --color nginx|$<\/pre>\n<h3>22. \"Find\" files with grep<\/h3>\n<p>The grep command can be used to search for files and this makes it a really powerful tool. Usually you would use the <a class=\"link-post\" href=\"https:\/\/www.binarytides.com\/linux-find-command-examples\/\">find command to search for files<\/a> from the command line on linux. However even grep can come in handy for the same task if used correctly.<\/p>\n<p>The basic idea is to use the output of the ls command and filter it using grep. Here is a quick example<\/p>\n<pre class=\"terminal\" >$ ls -lR \/etc\/ | grep conf | head -n5\r\n-rw-r--r-- 1 root          root           3028 Aug  9  2022 adduser.conf\r\n...<\/pre>\n<p>We recursively list all files with ls and then we feed the output to grep, and search for conf in their names. We limit the output to only 5 entries with the head command.<\/p>\n<h3>23. Searching archives<\/h3>\n<p>The grep command can search for patterns in regular files. But what if you want to search files that compressed ? For example log files on linux system are often split and compressed. Apache access and error log files are stored like this for example.<\/p>\n<p>The \"zgrep\" command can be used to search compressed files in nearly the same way as grep would search a regular file.<\/p>\n<p>In order to search in archives, we will use the zgrep equivalent exactly as we used grep. This is another very useful tip in production environments where logs are many times archived.<\/p>\n<pre class=\"terminal\" >$ zgrep -i &#039;get&#039; \/var\/log\/apache2\/*<\/pre>\n<p>Here is another example. Grepping for errors and warnings in syslog archived files and non archived files:<\/p>\n<pre class=\"terminal\" >$ zgrep -i &#039;error\\|warning&#039; \/var\/log\/syslog*\r\n...<\/pre>\n<h3>Conclusion<\/h3>\n<h4>1. Variations of grep<\/h4>\n<p>There are many variations of the grep command like egrep, zgrep etc. Each variation supports different features beyond the base grep command. Use the apropos command to get a list of all grep variants.<\/p>\n<pre class=\"terminal\" >$ apropos grep\r\nbzegrep (1)          - search possibly bzip2 compressed files for a regular expression\r\nbzfgrep (1)          - search possibly bzip2 compressed files for a regular expression\r\nbzgrep (1)           - search possibly bzip2 compressed files for a regular expression\r\negrep (1)            - print lines that match patterns\r\nfgrep (1)            - print lines that match patterns\r\ngit-bugreport (1)    - Collect information for user to file a bug report\r\ngit-grep (1)         - Print lines matching a pattern\r\ngrep (1)             - print lines that match patterns\r\nlzegrep (1)          - search compressed files for a regular expression\r\nlzfgrep (1)          - search compressed files for a regular expression\r\nlzgrep (1)           - search compressed files for a regular expression\r\npgrep (1)            - look up, signal, or wait for processes based on name and other attributes\r\nptargrep (1)         - Apply pattern matching to the contents of files in a tar archive\r\nrgrep (1)            - print lines that match patterns\r\nxzegrep (1)          - search compressed files for a regular expression\r\nxzfgrep (1)          - search compressed files for a regular expression\r\nxzgrep (1)           - search compressed files for a regular expression\r\nzegrep (1)           - search possibly compressed files for a regular expression\r\nzfgrep (1)           - search possibly compressed files for a regular expression\r\nzgrep (1)            - search possibly compressed files for a regular expression\r\nzstdgrep (1)         - print lines matching a pattern in zstandard-compressed files<\/pre>\n<p>Out of all the commands above the most popular one is zgrep, and its position is well worth it since it spares us from unfolding archives and deleting afterwards. <\/p>\n<p>The version of grep available in Ubuntu 22.04 LTS, a popular Linux distribution is 3.7:<\/p>\n<pre class=\"terminal\" >$ apt info grep\r\nPackage: grep\r\nVersion: 3.7-1build1\r\n&hellip;.<\/pre>\n<p>If you want to have the latest version, you can compile it from sources from this url, at the time of this writing 3.8: https:\/\/git.savannah.gnu.org\/cgit\/grep.git\/snapshot\/grep-3.8.tar.gz<\/p>\n<h4>2. Tips<\/h4>\n<p>Tips:<br \/>\ngrep returns 0 if it matches your query, and non-zero if it does not!<\/p>\n<p>Now you have all the basics and even advanced usages of grep to search files and logs on your system.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Grep Command Grep command in Linux is primarily used to search files for specific patterns of text, but there is a lot more it can do. The name \u201cgrep\u201d is derived from the command used to perform a similar operation &#8220;ed&#8221; text editor with the operation: g\/re\/p ((globally search for a regular expression and print&#8230; <span class=\"read-more\"><a href=\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":15958,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[855],"tags":[],"class_list":["post-14568","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linux-commands"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>21+ Grep Command Examples in Linux - Searching text patterns in files - BinaryTides<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Silver Moon\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"21 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/\",\"url\":\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/\",\"name\":\"21+ Grep Command Examples in Linux - Searching text patterns in files - BinaryTides\",\"isPartOf\":{\"@id\":\"https:\/\/www.binarytides.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg\",\"datePublished\":\"2023-02-18T07:34:10+00:00\",\"author\":{\"@id\":\"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd\"},\"breadcrumb\":{\"@id\":\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#primaryimage\",\"url\":\"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg\",\"contentUrl\":\"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg\",\"width\":1920,\"height\":1080},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.binarytides.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"21+ Grep Command Examples in Linux &#8211; Searching text patterns in files\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.binarytides.com\/#website\",\"url\":\"https:\/\/www.binarytides.com\/\",\"name\":\"BinaryTides\",\"description\":\"News, Technology, Entertainment and more\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.binarytides.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd\",\"name\":\"Silver Moon\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.binarytides.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g\",\"caption\":\"Silver Moon\"},\"description\":\"A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at binarytides@gmail.com.\",\"url\":\"https:\/\/www.binarytides.com\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"21+ Grep Command Examples in Linux - Searching text patterns in files - BinaryTides","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/","twitter_misc":{"Written by":"Silver Moon","Est. reading time":"21 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/","url":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/","name":"21+ Grep Command Examples in Linux - Searching text patterns in files - BinaryTides","isPartOf":{"@id":"https:\/\/www.binarytides.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#primaryimage"},"image":{"@id":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#primaryimage"},"thumbnailUrl":"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg","datePublished":"2023-02-18T07:34:10+00:00","author":{"@id":"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd"},"breadcrumb":{"@id":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#primaryimage","url":"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg","contentUrl":"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg","width":1920,"height":1080},{"@type":"BreadcrumbList","@id":"https:\/\/www.binarytides.com\/grep-command-examples-in-linux\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.binarytides.com\/"},{"@type":"ListItem","position":2,"name":"21+ Grep Command Examples in Linux &#8211; Searching text patterns in files"}]},{"@type":"WebSite","@id":"https:\/\/www.binarytides.com\/#website","url":"https:\/\/www.binarytides.com\/","name":"BinaryTides","description":"News, Technology, Entertainment and more","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.binarytides.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd","name":"Silver Moon","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.binarytides.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g","caption":"Silver Moon"},"description":"A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at binarytides@gmail.com.","url":"https:\/\/www.binarytides.com\/author\/admin\/"}]}},"_links":{"self":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/posts\/14568","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/comments?post=14568"}],"version-history":[{"count":18,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/posts\/14568\/revisions"}],"predecessor-version":[{"id":14594,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/posts\/14568\/revisions\/14594"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/media\/15958"}],"wp:attachment":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/media?parent=14568"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/categories?post=14568"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/tags?post=14568"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}