【问题标题】:How to pass conditions to "for" loop command in bash?如何在bash中将条件传递给“for”循环命令?
【发布时间】:2015-11-15 08:57:12
【问题描述】:

我想将条件传递给lsfor 命令来执行以下操作:

for file in *.jpg OR *.jpeg OR *.JPG OR *.JPEG;do
done

我尝试使用|||OR[] 来关闭条件,但没有成功。

谢谢。

【问题讨论】:

    标签: bash for-loop ls conditional


    【解决方案1】:

    这很容易:

    for file in *.jpg *.jpeg *.JPG *.JPEG; do
    ...
    done
    

    或:

    for file in *.{jpg,jpeg,JPG,JPEG}; do
    ...
    done
    

    更多示例请参见此处:http://www.tldp.org/LDP/abs/html/loops1.html

    但是,我的第一选择始终是:

    ls -1 | egrep -i '.jpg|.jpeg' | while read file; do
    
    done
    

    附录 TEST1

    如果有人担心特殊字符,这些是 som 测试:

    ls -1:

    with?newline
    without
    with space
    with?tab
    

    用于*中的文件;做回声“:::$file:::”;完成

    :::with
    newline:::
    :::without:::
    :::with space:::
    :::with tab:::
    

    ls -1 |读取文件时;做回声“:::$file:::”;完成

    :::with:::
    :::newline:::  <= ERROR
    :::without:::
    :::with space:::
    :::with tab:::
    

    附录 TEST2

    对于担心目录中文件数量的人,这些是在包含 62380 个以“文件...”开头的长名称文件的目录中进行的一些测试:

    $ ls -1 file* | wc -l
    bash: /bin/ls: Argument list too long <= ERROR
    0
    
    $ ls -1 | egrep '^file' | while read i; do echo $i; done | wc -l
    62380
    
    $ for i in file*; do echo $i; done | wc -l
    62380
    

    【讨论】:

    • @tripleee:根据我的个人经验,我在使用 ARG_MAX 时遇到了一些问题,而对于包含换行符的文件名则没有。
    【解决方案2】:
    for file in *.{jpg,jpeg,JPG,JPEG}; do
        # Do stuff
    done
    

    这可能是最简洁、可读和可维护(可修改)的解决方案。

    正如triplee 所指出的,大括号扩展仅在Bash 中可用(提问者已指定),因此在某些情况下其他人可能需要使用:

    for file in *.jpg *.jpeg *.JPG *.JPEG; do
        # Do stuff
    done
    

    【讨论】:

    • 甚至 more 简洁:shopt -s nocaseglob; for file in *.{jp{,e}g}; do :) 不过,这相当不可读,所以我将其拨回for file in *.{jpg,jpeg}; do
    • @chepner concise: adj. Expressing much in few words; clear and succinct. 在这种特殊情况下,只有 4 种可能性,我觉得你的解决方案有点矫枉过正!
    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 2016-01-12
    • 2014-10-05
    • 1970-01-01
    • 2015-11-16
    • 2019-01-31
    • 2018-02-13
    • 2023-04-05
    相关资源
    最近更新 更多