循环浏览具有特定扩展名的所有文件 [英] Loop through all the files with a specific extension

查看:74
本文介绍了循环浏览具有特定扩展名的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for i in $(ls);do
    if [ $i = '*.java' ];then
        echo "I do something with the file $i"
    fi
done

我想遍历当前文件夹中的每个文件,并检查其是否与特定扩展名匹配.上面的代码不起作用,你知道为什么吗?

I want to loop through each file in the current folder and check if it matches a specific extension. The code above doesn't work, do you know why?

推荐答案

无需花哨的技巧:

for i in *.java; do
    [ -f "$i" ] || break
    ...
done

警卫人员确保如果没有匹配的文件,则循环将退出,而不会尝试处理不存在的文件名*.java.在bash(或支持类似功能的shell)中,可以使用nullglob选项 只是忽略匹配失败而不会进入循环的正文.

The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java. In bash (or shells supporting something similar), you can use the nullglob option to simply ignore a failed match and not enter the body of the loop.

shopt -s nullglob
for i in *.java; do
    ...
done

这篇关于循环浏览具有特定扩展名的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆