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

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

问题描述

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天全站免登陆