Bash 获取具有所需扩展名的所有文件的脚本

Bash script to get all file with desired extensions

我正在尝试编写一个 bash 脚本,如果我传递一个包含一些扩展名的文本文件和一个文件夹 returns 我一个输出文件,其中包含与所需的所有文件的列表扩展,在所有子目录中递归搜索

文件夹是我的第二个参数扩展列表文件我的第一个参数

我试过:

for i in  ; do
   find . -name \*.$i -print>>result.txt
done

但不起作用

试试这个单行命令。

/mydir 替换为要搜索的文件夹。

更改作为参数传递给 egrep 命令的扩展列表:

find /mydir -type f | egrep "[.]txt|[.]xml" >> result.txt

egrep之后,每个分机都要用|隔开。

. 字符必须使用 [.]

进行转义

如评论中所述:

写入硬编码文件名不是一个好主意。 给定的示例仅修复了 OP 问题中的给定代码。 是的,当然,用

调用更好
x.sh y . > blabla

并从脚本本身中删除文件名。但我的意图不是解决问题...

以下bash脚本,命名为x.sh

#!/bin/bash
echo -n >result.txt                             # delete old content
while read i; do                                # read a line from file
       find  -name \*.$i -print>>result.txt   # for every item do a find
done <                                        # read from file named with first arg from cmdline  

一个名为 y 的文本文件包含以下内容

txt
sh

并调用:

./x.sh y .

生成文件 result.txt,其内容为:

a.txt
b.txt
x.sh

好的,让我们从评论中获得一些额外的提示: 如果结果字段不应从脚本的其他结果中收集任何其他内容,则可以简化为:

#!/bin/bash
while read i; do                    # read a line from file
       find  -name \*.$i -print   # for every item do a find
done < >result.txt                # read from file named with first arg from cmdline

并且如前所述: 硬编码 result.txt 可以删除,调用可以是

./x.sh y . > result.txt