Sometimes when I run ls to get a directory listing, I am looking for a specific file, but I want to see the whole context where the file resides. While you can pipe the output of ls to grep, that doesn't show you the whole directory with the matched files highlighted in a different color. I create a small script to do just what I want.
For example, suppose that in /proc/sys/net/ipv4 I want to see files that have the pattern "max" as part of the name. I could run
ls /proc/sys/net/ipv4 | grep max. grep changes the color to red where the pattern is found, but it doesn't display the files I want in the context of the entire directory listing. The following script does:
# name of the script 'l' just the letter l
# a little bit of help in case of misuse
if [ $# -lt 2 ]
echo "usage: l /directory pattern"
echo "example: l /etc config"
# $DIR is the first argument, the path to the directory
# $SEARCH is what you are looking for, and it's the second argument
# $RED sets the text to inverted red, changing the capabilities of the terminal via terminfo parameters
# setaf 1 = red, smso = inverted
RED=`tput setaf 1; tput smso`
# $NORMAL returns text to normal attributes
ls -C $DIR | sed s/"$SEARCH"/"$RED$SEARCH$NORMAL"/
tput is a command that allows you to change the capabilities of the terminal, not just set the colors; it's based on the terminfo database. I use
ls Ã¢â¬âC to put the directory listing in columns even if it's piped or redirected, so I can see more on a single screen. Then a simple
sed substitution statement does the job; it finds whatever $SEARCH holds and substitutes for the same pattern with a change of color.
To make the script available to all users, copy it to /usr/bin and change the permissions (
chmod 4755 /usr/bin/l). You can then run it like this:
l /etc conf
Customizing a directory listing may not be a very important issue, but thanks to the flexibility of Linux, you can increase your productivity with little tweaks.