| 226 | The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for global search for regular expression and print out). |
| 227 | Syntax: |
| 228 | |
| 229 | grep [options] pattern [files] |
| 230 | |
| 231 | 1. Case insensitive search : The -i option enables to search for a string case insensitively in the given file. It matches the words like “UNIX”, “Unix”, “unix”. |
| 232 | |
| 233 | `$grep -i "UNix" file.txt` |
| 234 | |
| 235 | 2. Displaying the count of number of matches : We can find the number of lines that matches the given string/pattern |
| 236 | |
| 237 | `$grep -c "unix" file.txt` |
| 238 | |
| 239 | 3. Display the file names that matches the pattern : We can just display the files that contains the given string/pattern. |
| 240 | |
| 241 | `$grep -l "unix" *` |
| 242 | |
| 243 | or |
| 244 | |
| 245 | `$grep -l "unix" f1.txt f2.txt f3.xt f4.txt` |
| 246 | |
| 247 | 4. Checking for the whole words in a file : By default, grep matches the given string/pattern even if it is found as a substring in a file. The -w option to grep makes it match only the whole words. |
| 248 | |
| 249 | `$ grep -w "unix" file.txt` |
| 250 | |
| 251 | 5. Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option. |
| 252 | |
| 253 | `$ grep -o "unix" file.txt` |
| 254 | |
| 255 | 6. Show line number while displaying the output using grep -n : To show the line number of file with the line matched. |
| 256 | |
| 257 | `$ grep -n "unix" file.txt` |
| 258 | |
| 259 | 7. Inverting the pattern match : You can display the lines that are not matched with the specified search string pattern using the -v option. |
| 260 | |
| 261 | `$ grep -v "unix" file.txt` |
| 262 | |
| 263 | 8. Matching the lines that start with a string : The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern. |
| 264 | |
| 265 | `$ grep "^unix" file.txt` |
| 266 | |
| 267 | 9. Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern. |
| 268 | |
| 269 | `$ grep "os$" file.txt` |
| 270 | |
| 271 | 10.Specifies expression with -e option. Can use multiple times : |
| 272 | |
| 273 | `$grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" file.txt` |
| 274 | |
| 275 | 12. Search recursively for a pattern in the directory: -R prints the searched pattern in the given directory recursively in all the files. |
| 276 | |
| 277 | Syntax |
| 278 | |
| 279 | `$grep -R [Search] [directory]` |
| 280 | |