【问题标题】:Loop through all files in a directory?遍历目录中的所有文件?
【发布时间】:2015-03-05 12:25:21
【问题描述】:
FILES="$DIRECTORY"/*
for f in $FILES
do
echo "file $f: "
#ls "$f"
done

我正在尝试遍历文件以分别显示每个文件的信息。例如

first file
name
size
date edited

转到下一个文件的选项。

second file
name
size
date edited

等等,虽然它现在只是显示这个:

file/dir/file1
file/dir/file2

编辑:

是的,我已经对此进行了更多研究,现在有了这个。

total=$(find $DIRECTORY -type f | wc -l)
f="1"
while [ $f -lt $total ]
do
echo "file $f: "
stat %n $f
f=$[$f+1]
done

这应该做的是获取目录中的文件总数,然后遍历它们。问题是我不知道如何让文件信息显示在它们上面。

file 0:
stat: cannot stat ‘%n’: No such file or directory
stat: cannot stat ‘0’: No such file or directory
file 1:
stat: cannot stat ‘%n’: No such file or directory
stat: cannot stat ‘1’: No such file or directory

【问题讨论】:

  • 查看man stat
  • $[...] 已过时;请改用$((...))

标签: linux bash shell loops sh


【解决方案1】:

如果您只想要名称、大小和 mtime,请尝试:

find "$DIRECTORY" -maxdepth 1 -type f -exec sh -c 'stat -c "%n %s %y" "$0"' {} \;

【讨论】:

  • 或者,如果 find 支持 -printf 以及所有 GNU 好东西:find "$DIRECTORY" -maxdepth 1 -type f -printf '%f %s %t\n'
猜你喜欢
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 2012-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多