bash for 迴圈中 find 指令的參考項

bash for 迴圈中 find 指令的參考項

假設我有這樣的程式碼:

for i in $(find * -type f -name "*.txt"); do 
  # echo [element by it's index]
done

如果可能的話,如何透過索引存取元素?

答案1

你的命令

$(find * -type f -name "*.txt")

將會傳回一個(空格分隔的)bash 列表,而不是數組,因此您無法真正以「目標」方式存取各個元素。

若要將其轉換為 bash 數組,請使用

filearray=( $(find * -type f -name "*.txt") )

(注意空格!)

然後,您可以存取各個條目,如下所示

for ((i=0; i<n; i++))
do
   file="${filarray[$i]}"
   <whatever operation on the file>
done

可以透過以下方式檢索條目數

n="${#filearray[@]}"

但請注意那個這個僅有的如果您的檔案名稱不包含特殊字元(特別是空格),則可以使用,因此,再一次,不建議解析lsor的輸出find。就您而言,我建議您查看該-exec選項是否find可以完成您需要完成的任務。

相關內容