gpt4 book ai didi

python - 用于在文件夹中查找文件的 Bash 脚本

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:18 27 4
gpt4 key购买 nike

我有几个文件夹作为

Main/  
/a
/b
/c
..

我必须分别将这些文件夹中的输入文件 abc1.txtabc2.txt 作为输入文件传递给我的 python 程序。现在的脚本是,

for i in `cat file.list`
do
echo $i
cd $i
#works on the assumption that there is only one .txt file
inputfile=`ls | grep .txt`
echo $inputfile
python2.7 ../getDOC.py $inputfile
sleep 10
cd ..
done
echo "Script executed successfully"

因此,无论 .txt 文件的数量如何,我都希望脚本能够正常工作。

如果有多个 .txt 文件,任何人都可以告诉我 shell 中是否有任何内置命令来获取正确的 .txt 文件?

最佳答案

find 命令非常适合与 -exec 配合使用:

find /path/to/Main -type f -name "*.txt" -exec python2.7 ../getDOC.py {} \; -exec sleep 10 \;

解释:

  • find - 调用find
  • /path/to/Main - 开始搜索的目录。默认情况下,find 递归搜索。
  • -type f - 只考虑文件(而不是目录等)
  • -name "*.txt" - 只查找扩展名为 .txt 的文件。这是引用所以 bash 不会通过通配符自动扩展通配符 *
  • -exec ...\; - 对于找到的每个这样的结果,对其运行以下命令:
  • python2.7 ../getDOC.py {}; - {} 部分是 find 的搜索结果获取的地方代入每次。
  • sleep 10 - 每次在文件上运行 python 脚本后休眠 10 秒。如果您不想让它休眠,请将其移除。

关于python - 用于在文件夹中查找文件的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com