我有以下代码
arrFiles[0]=0
cd "/home/thenok/Documents/Link to thought diary"
for i in $(find -type f ! -name "*~"); do
arrFiles[0]=$[arrFiles[0]+1]
arrFiles[arrFiles[0]]="$i"
echo " pos ${arrFiles[0]} file ${arrFiles[arrFiles[0]]}"
done
但它输出到(13 和 23 是文件)
pos 354 file ./Link
pos 355 file to
pos 356 file diary/201504/quint/13
pos 357 file ./Link
pos 358 file to
pos 359 file diary/201511/23
这很糟糕,因为当使用另一个命令(stat)而不是 echo 时,它会给我
stat: cannot stat ‘./Link’: No such file or directory
stat: cannot stat ‘to’: No such file or directory
stat: cannot stat ‘thought’: No such file or directory
stat: cannot stat ‘diary/201411/done/31’: No such file or directory
我尝试过:1:使用直接路径而不是链接,2:
arrFiles[0]=0
FILES="/home/thenok/Documents/Link to thought diary/*"
for i in "$FILES"; do
arrFiles[0]=$[arrFiles[0]+1]
arrFiles[arrFiles[0]]="$i"
echo " pos ${arrFiles[0]} file ${arrFiles[arrFiles[0]]}"
done
#result is pos 1 file /home/thenok/Documents/Link to thought diary/*
3:直接创建阵列而不使用子文件夹
arrFiles=( "/home/thenok/Documents/Link to thought diary/"* )
for f in "${arrFiles[@]}"
do
stat -c %s "$f"
echo "$f"
done
解决方案位于如何在带有空格的“for”循环中读取完整行这正是我最初想要的,但我不知道如何在谷歌中写入
IFS=$'\n' # make newlines the only separator
arrFiles[0]=0
cd "/home/thenok/Documents/Link to thought diary"
for i in $(find "/home/thenok/Documents/Link to thought diary/" -type f ! -name "*~"); do
arrFiles[0]=$[arrFiles[0]+1]
arrFiles[arrFiles[0]]="$i"
echo " pos ${arrFiles[0]} file ${arrFiles[arrFiles[0]]}"
done
输出是
pos 10 file /home/thenok/Documents/Link to thought diary/Link to diary/201408/methinks questions.txt
pos 11 file /home/thenok/Documents/Link to thought diary/Link to diary/201408/methinks small.txt
pos 12 file /home/thenok/Documents/Link to thought diary/Link to diary/201408/methinks2.txt
pos 13 file /home/thenok/Documents/Link to thought diary/Link to diary/201408/methinkss.txt
pos 14 file /home/thenok/Documents/Link to thought diary/Link to diary/201408/myfile.txt
pos 15 file /home/thenok/Documents/Link to thought diary/Link to diary/201408/new 2.txt
答案1
这样做:
FILES="/home/thenok/Documents/Link to thought diary/"
for f in "$FILES"/*
do
stat "$f"
done
如果使用find
,请使用其-exec
命令:
find "/home/thenok/Documents/Link to thought diary/" -type f ! -name '*~' -exec stat {} +
如果需要数组,直接创建一个即可:
arrFiles=( "/home/thenok/Documents/Link to thought diary/"* )
然后做:
for f in "${arrFiles[@]}"
do
stat -c %s "$f"
done
而不是循环索引。即使这样,您也不需要手动保存数组的长度。您可以通过 来获取它${#arrFiles[@]}
。