For programmers who do not like to use IDEs, it may not be convenient to find specific strings in files of a specified type. Using standard grep is an option, but specifying file types can be quite cumbersome. We can solve this with a small script. First, use find to list the filenames we need to search for, each on a new line, and save them in a text file:

find -iname *.v > /tmp/1.txt
find -iname *.vhd >> /tmp/1.txt

And here's the script:

#!/usr/bin/lua

file = io.open(arg[1], "r")
good=0
files=""

for line in file:lines() do
    cmd=string.format("grep %s '%s' ", arg[2], line)
    reti=os.execute(cmd)
    if(reti)then
        print(string.format("Good %s", line))
        good=good+1
        files=files .. line .. "\n"
    else
        print(string.format("Bad %s, found=%d", line, good))
    end
end

print(string.format("Found %d files: ", good))
print(files)
file:close()

The advantage is that if there are many files, you can see the search results dynamically without having to wait for a long time.

~/f.lua /tmp/1.txt i_tcp_en

Found 7 files: 
./header_gen/source/header_100ge_gen.v
./header_gen/source/header_100ge_gen_debug.v
./header_gen/source/header_100ge_gen_tcp_flooding_1.v
./header_gen/source/header_100ge_gen_tcp_flooding_10.v
./header_gen/source/header_100ge_gen_tcp_flooding_32.v
./payload_gen/source/payload_100ge_gen_v1.v
./tx_top/source/tx_100ge_top.v

2024-11-11_11-11-1731295974.png

You can do this with xargs

find . -name "*.c" | xargs -d'\n' grep -w "main"

Or if you know you want to search the same set of files many times.

find . -name "*.c" > tmp.txt
xargs --arg-file=tmp.txt grep -w "main"
xargs --arg-file=tmp.txt grep -w "void"
commented: Thank you for your improvement plan. Using xargs avoids repeatedly loading grep and running it, thus improving efficiency. +0

Thank you, Salem. The script has been modified and the efficiency has been increased by more than 50%.

#!/bin/sh

#
# search text pattern in current directory.
# usage:  f pattern [file]
#

params="-E -n --color=auto"

if [ "${2}" == "" ]; then
    find -iname "*.c" -or -iname "*.cpp" -or -iname "*.h" -or -iname "*.mak" -or -iname "Makefile" -or -iname "*.s" | xargs -d'\n' grep $params "$1"
    exit $?
fi

case "${2}" in
c)
    find -iname "*.c" -or -iname "*.cpp" | xargs -d'\n' grep $params "$1"
    ;;
make)
    find -iname  "*.mak" -or -iname "Makefile" | xargs -d'\n' grep $params "$1"
    ;;
h)
    find  -iname "*.h" | xargs -d'\n' grep $params "$1"
    ;;
v)
    find  -iname "*.v" | xargs -d'\n' grep $params "$1"
    ;;
vhd)
    find  -iname "*.vhd" | xargs -d'\n' grep $params "$1"
    ;;
all)
    grep -R $params "$1" .
    ;;
*)
    find -iname "*${2}*" | xargs -d'\n' grep $params "$1"
    ;;

esac
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.