Bash: loop through files that DO NOT match extension

后端 未结 6 400
眼角桃花
眼角桃花 2021-01-13 17:32

I\'m writing a bash script that needs to loop files inside a directory that do not match a specific extension. So far, I\'ve found that the following code loops all files th

6条回答
  •  Happy的楠姐
    2021-01-13 18:09

    This will do:

    shopt -s extglob
    for f in !(*.txt) ; do
        echo $f
    done
    

    You just inverse the glob pattern using !(glob_pat), and to use it, you need to enable extended glob.

    If you want to ignore directories, then:

    shopt -s extglob
    for f in !(*.txt) ; do
        [ -d "$f" ] && continue   # This will ignore dirs
        # [ -f "$f" ] && continue # This will ignore files
        echo $f
    done
    

    If you wanna go into all sub-dirs then:

    shopt -s extglob globstar
    for f in !(*.txt) **/!(*.txt) ; do
        [ -d "$f" ] && continue   # This will ignore dirs
        # [ -f "$f" ] && continue # This will ignore files
        echo $f
    done
    

提交回复
热议问题