Introduction
The grep
command enables us to apply some regex matching of patterns to the contents of a text file from the terminal with the help of the Unix pipe operator ( |
). The grep
command can also be used on its own.
The pipe operator ( |
) works like this, take the outputs of the first command and “pipe”, and apply the outputs as inputs to the second command in one line.
The general format using the grep command is:
grep [options] pattern [file]
1. Example usage of the grep
command with the pipe operator (|
)
Take for instance a file list.json
:
nmurgor@nmurgor:$ cat list.json | grep Kenya
# outputs:
"Kenya": "KE",
The cat
command displays the contents of a text file to the terminal. We take this output and “pipe” to the grep
command to see if the text “Kenya” is in the contents of the list.json
2. Example usage of the grep
command
nmurgor@nmurgor:$ grep Ke* list.json
# outputs
"Comoros": "KM",
"Kenya": "KE",
Bonus, you can use standard regex to match patterns in the text file to increase accuracy.
The contents of the list.json
file look like this:
{
"Burundi": "BI",
"Comoros": "KM",
"Djibouti": "DJ",
"Eritrea": "ER",
"Ethiopia": "ET",
"Kenya": "KE",
"Madagascar": "MG",
"Malawi": "MW",
"Mauritius": "MU",
"Mozambique": "MZ",
"Rwanda": "RW",
"Seychelles": "SC",
"Somalia": "SO",
"South Sudan": "SS",
"Tanzania": "TZ",
"Uganda": "UG"
}
Follow me on twitter @nkmurgor where I tweet about interesting topics.