How To Search With Grep, Pipes & Wc In Shell (Terminal) Command (CLI)

Follow Us on Social Media

How To Search With Grep, Pipes & Wc In Shell (Terminal) Command (CLI)

How To Search With Grep, Pipes & Wc In Shell (Terminal) Command (CLI)

You can simplify the task of searching by using simple commands in the CLI.
The grep, and wc, as well as the pipes commands make searching via the terminal easy.

"GREP" is short for Global Regular Expression Print. This terminal command processes text line by line, and prints out any lines which match a specified pattern. While using grep, you'll usually specify the term to search for. 

"WC" which stands for Word Count, helps to execute word count, new line count, as well as byte count.

To search using grep, type:

grep word_to_search file_to_seach_word_in

E.g.: grep John bible.txt

We can use the pipe command to pipe the output of our grep command to the less program instead of displaying it directly in the terminal.

This helps to simplify the list outputs, and could be useful where there are several outputs, so we can scroll through the list of outputs page by page.

To pipe our result, we will use the pipe command which is the vertical bar located on your keyboard to the right (|).

E.g.: grep John bible.txt | less


With the script, we piped the output of the grep to the less interface, instead of outputting directly to the terminal.

Grep could also be used with a url directly. Much like querying files from the internet rather than download such files locally before executing queries.

For that, we'll use:

curl -L https://tinyurl.com/bible.txt | grep -c John

With the above script, we searched for the word "John" directly from a file on the internet at 'https://tinyurl.com/bible.txt.

The 'wc' in the script tells grep to count the number of words, while '-l' tells it to display the number of lines.

Another way to execute a word count on the above script would be:


curl -L https://tinyurl.com/bible.txt | grep wc John 



No comments



Powered by Blogger.