簡體   English   中英

如何捕獲ls或find命令的輸出以將所有文件名存儲在數組中?

[英]How do I capture the output from the ls or find command to store all file names in an array?

需要一次處理一個當前目錄中的文件。 我正在尋找一種方法來獲取ls的輸出或find並將結果值存儲為數組的元素。 這樣我就可以根據需要操作數組元素。

要回答您的確切問題,請使用以下內容:

arr=( $(find /path/to/toplevel/dir -type f) )

$ find . -type f
./test1.txt
./test2.txt
./test3.txt
$ arr=( $(find . -type f) )
$ echo ${#arr[@]}
3
$ echo ${arr[@]}
./test1.txt ./test2.txt ./test3.txt
$ echo ${arr[0]}
./test1.txt

但是,如果你只想一次處理一個文件,你可以使用find-exec選項,如果腳本有點簡單,或者你可以循環查找返回的內容,如下所示:

while IFS= read -r -d $'\0' file; do
  # stuff with "$file" here
done < <(find /path/to/toplevel/dir -type f -print0)
for i in `ls`; do echo $i; done;

不能比那更簡單!

編輯:嗯 - 根據丹尼斯威廉姆森的評論,似乎你可以!

編輯2:雖然OP專門詢問如何解析ls的輸出,但我只想指出,正如下面的評論員所說,正確答案是“你沒有”。 for i in *或類似的for i in *

實際上,您不需要在當前目錄中使用ls / find for files。

只需使用for循環:

for files in *; do 
    if [ -f "$files" ]; then
        # do something
    fi
done

如果您也想處理隱藏文件,可以設置相對選項:

shopt -s dotglob

最后一個命令僅適用於bash。

根據您的想法,您可以使用xargs:

ls directory | xargs cp -v dir2

例如。 xargs將對返回的每個項目執行操作。

暫無
暫無

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

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