find 命令的管道輸出

find 命令的管道輸出

繼我發布的查詢之後 - 將 find 與 sh - 指令一起使用不起作用

根據以下命令的 o/p,我需要將列出的每個檔案的權限更新為 777。

find . -type f -name '*FW*' -exec grep -iEq 'chmod.*archive|archive.*chmod' {} \; -ls

有什麼方法可以將輸出傳輸到檔案chmod並更新檔案權限嗎?

答案1

您可以新增另一個-exec來對文件find執行。如果不需要,chmod請刪除:-ls

find . -type f -name '*FW*' -exec grep -iEq 'chmod.*archive|archive.*chmod' {} \;\
  -ls -exec chmod 777 {} +

答案2

您可以-exec在末尾添加另一個來更新通過前面測試的文件的權限,就像佛萊迪的表演,或者您可以將grep和組合chmod在內聯腳本中sh -c

find . -type f -name '*FW*' -exec sh -c '
    for pathname do
        if grep -q -i -e "chmod.*archive" -e "archive.*chmod" "$pathname"
        then
            chmod 777 "$pathname"
        fi
    done' sh {} +

這將用作腳本find中循環的路徑名產生器sh -c

此循環取得賦予內聯腳本的所有路徑名,使用 測試每個路徑名grep,如果模式在檔案中匹配,則該檔案的權限(可能)會更新。


在 中,您可以使用檔案名稱通配模式,bash而不是透過 產生路徑名稱:find

shopt -s globstar nullglob dotglob

for pathname in ./**/*FW*; do
    if [ -f "$pathname" ] && grep -q -i -e 'chmod.*archive' -e 'archive.*chmod' "$pathname"
    then
        chmod 777 "$pathname"
    fi
done

這裡唯一可見的區別是,這也將處理與模式相符的符號連結。

shellglobstar選項啟用**遞歸匹配子目錄的模式。 shellnullglob選項使不匹配的模式消失,而不是保持未展開狀態。 shelldotglob選項使模式與隱藏名稱相符。

zshshell 中,這可以縮短為

for pathname in ./**/*FW*(.ND); do
    if grep -q -i -e 'chmod.*archive' -e 'archive.*chmod' $pathname
    then
        chmod 777 $pathname
    fi
done

....其中.,ND依序對應於-f測驗(但不會符合符號連結)、設定nullglobdotglob設定bash

相關內容