2021年8月4日 星期三

Linux command : find and grep

 I like to use ripgrep, like its format and colors. 

For example:

find ./ -name "*" -type f -size -20k| xargs rg -n -C2 "index"

or

find ./ -name "*" -type f -size -20k| xargs rg -n -C2 2>/dev/null "index"



But it may not be available in Ubuntu 12.04. To write a script to execute grep, 
you can get output similar to ripgrep. Unlike ripgrep, the file name is printed on the bottom line. As follows:

find ./ -name "*" -type f -size -20k| while read file; do if grep -n -C2 "index" $file; then echo -e "\033[35m $file\n \033[0m"; fi done

Filter out "No such file or directory" messages:
find ./ -name "*" -type f -size -20k| while read file; do if grep -s -n -C2 "index" $file; then echo -e "\033[35m $file\n \033[0m"; fi done

You can also write a script to improve grep:
cd ~/
vi impgrep
#!/bin/sh
while read file; do if grep --color=auto "$@" $file; then echo -e "\033[35m $file\n \033[0m"; fi done

chmod 755 impgrep

Usage example:
find ./ -name "*.c" -o -name "*.h"|~/impgrep -s -n -C2 "index"