<<< Back to Tips Index

15 May 2015

Nifty use of grep in a loop

Grep is a widely known and used tool, but here is a use that you may not have considered before.

GNU's grep, as used in Linux systems, and also available on some Unix systems (it may be installed as ggrep), has some additional features, one of which is --color, which can be used to highlight the matching section of the line.

For example, here it's showing where the word "file" is found in a file.

grep output

That is handy, but it's not the neat bit. Here it comes: You can use this to highlight a given item in a list.

A loop might configure and build some software, then package it up, distribute it and install it on client systems. It's quite a time-consuming process, and you want to easily be able to check on its progress. By using grep --color, we can automatically highlight the current step in the process.

grep output

Now, each step (configure, make, package, distriute, install) is highlighted, simply by using grep:
echo "${STEPS}" | grep --color ${ACTION}
This echoes out the full list of steps (of course, it's only one line), and then uses grep to match the individual step (the line is guaranteed to match, so the line always gets displayed, which makes the grep seem rather useless. The only thing we're gaining, is that GNU grep also does this colour highlighting, causing the current action to be highlighted in red text.

Note: The other text, "Running ${ACTION}" is just a placeholder to show you where some other script output might go.

Download grep-loops.sh script
#!/bin/bash

STEPS="configure make package distribute install"
for ACTION in $STEPS
do
  echo "*****************************************"
  printf "*** Running action: %-15s (" *${ACTION}*
  echo "${STEPS})" | grep --color ${ACTION}
  echo "Running ${ACTION} ... Running ${ACTION} ... "
  echo "Running ${ACTION} ... Running ${ACTION}"
  sleep 1
  echo
done

Invest in your career. Buy my Shell Scripting Tutorial today:

 

Steve's Bourne / Bash shell scripting tips
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon