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
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.