簡體   English   中英

Bash:循環遍歷與擴展名不匹配的文件

[英]Bash: loop through files that DO NOT match extension

我正在編寫一個bash腳本,需要在目錄中循環與特定擴展名不匹配的文件。 到目前為止,我發現以下代碼循環所有匹配給定擴展名的文件:

for f in *.txt ; do
    echo $f;
done

insthead如何循環遍歷與指定擴展名不匹配的文件?

您可以使用==運算符進行模式匹配。

for f in *; do
    [[ $f == *.txt ]] && continue
    # [[ $f != *.txt ]] || continue
    ...
done

如果這可能在空目錄中運行,則在循環之前使用shopt -s nullglob ,或者放入[ -e "$f" ] || continue 循環[ -e "$f" ] || continue (前者更可取,因為它可以避免不斷檢查文件是否存在。)

循環目錄中與特定擴展名不匹配的文件

你可以使用extglob

shopt -s extglob

for f in *.!(txt); do
    echo "$f"
done

pattern *.!(txt)將匹配所有帶點后的條目,並且點后沒有txt


編輯:請參閱下面的評論。 這是一個循環查看當前目錄中與特定擴展名不匹配的文件的find版本:

while IFS= read -d '' -r f; do
    echo "$f"
done < <(find . -maxdepth 1 -type f -not -name '*.txt' -print0)

find /path/to/look -type f -not -name "*.txt" -print0 | while read -r -d '' file_name
do
echo "$file_name"
done

當你的文件名可能是非標准的。

注意:

如果您不希望以遞歸方式搜索子文件夾中的文件,請包括-maxdepth 1
就在前-type f

這樣做:

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

你只需使用!(glob_pat)反轉glob模式,並使用它,你需要啟用擴展的glob。

如果要忽略目錄,則:

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

如果你想進入所有子目錄,那么:

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

如果您對GNU解決方案沒問題,請試試這個:

for f in $(find . -maxdepth 1 -type f \! -name \*.txt) ; do
  printf "%s\n" "${f}"
done

如果文件名中包含特殊字符,則會中斷,例如 (空間)。

對於安全的東西,仍然是GNU ,嘗試:

find . -maxdepth 1 -type f \! -name \*.txt -printf "%p\0" | xargs -0 sh -c '
    for f ; do
      printf "%s\n" "${f}"
    done' arg0
for f in $(ls --hide="*.txt")
do
    echo $f
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM