Archive for the ‘shell tips’ Category

Search command in Shell

I like the Zsh shell, I saw so many compliment about this shell in planets, or blogs. So I want to try the “monster”. In the configuration file .zshrc (take at school) I have a useful function name clean.

It’s look like that :
[franky] clean

removed: ./lib/toto~

removed: ./lib/.tata~

removed: ./toto~

The function look like that :
clean()

{

SEARCH='.'

if [ ${1} ]

then

SEARCH=${1}

fi

find ${SEARCH} -type f \( -name "*~" -or -name ".*~" -or -name "\#*" -or -name "\#.*" \) -exec rm -fv {} \;

}

So, I want to make a function, who works with the same method but it’s have to find word (or grep pattern) occurrences in file recursively and indicate the line number.

I find few solutions, I prefer the first (I’m not sure but it’s the faster I think).

The default PATH is the current directory ” . “.

grep -nr $PATTERN $PATH

grep -n $PATTERN `find $PATH -type f`

find $PATH -type f -exec grep -n $EXPRESSION {} +

But I’m not satisfying by the result, I learn few things about awk utilisation, and it was great for this case. The problem with awk is it can’t interpret the colour variable, so the awk line is not pretty.

search()

{

SEARCH="."

if [ $# = 0 ]

then

echo -e "Usage: search PATTERN [DIRECTORY]"

else

if [ $# = 2 ]

then

SEARCH=${2}

fi

grep -nI ${1} `find ${SEARCH} -type f 2>&/dev/null` 2>&/dev/null |\

grep '^\'${SEARCH} |\

grep -v '/\.' |\

awk -F: ' {print "\033[1m\33[7;33m"$2 "\033[0;39m" "\033[3m
\
033[1m " $1 "\033[0;31m \033[3m\n\t" $3"\33[0;39m"}'

fi

}

Maybe you should delete the “&” one bash.
The result look like that. (click to see large view)

For Archlinux user maybe you see the colour look like yaourt
That’s works on bash, zsh, and I haven’t test others for the moment, you can try and inform me of the comportment.
If you have emacs, nano, vi installed you can open the file with line option easily.
Example :
emacs, vi or nano +52 minishell/my.h