bash列出所有目录、子目录、文件夹、子文件夹然后输出到单独的文件

bash list all directories, subdirectories, folders, subfolders in then output to a separate file

我正在尝试创建两个非常相似的脚本。一个脚本是列出目录中的所有文件,然后是子目录、子目录的子目录,等等,直到没有更多的目录,然后将信息输出到一个日志文件,其路径名从我开始的目录开始.另一个脚本与上面的完全相同,但我需要它列出这些目录和子目录中的所有文件,而不是目录。我还需要从我开始的目录开始的路径名。但是,它们都需要在单独的日志文件中输出。

我需要在 sed 命令或与 android 兼容的 bash 命令中执行此操作。

/system/表示我要启动的目录

这仅输出 /system/ 中的目录并成功生成日志文件:

LOG_FILE=/data/local/log.log;
for d in /system/*; do [[ -f "$d" ]] || echo "$d" "$d"| tee -a $LOG_FILE; done

这只输出 /system/ 中的文件并成功生成日志文件:

LOG_FILE=/data/local/log.log;
for f in /system/*; do [[ -d "$f" ]] || echo "$f" "$f"| tee -a $LOG_FILE; done

不幸的是,我在这里或其他任何地方搜索如何正确执行此操作都没有成功。我几乎可以肯定我不能在我正在使用的 Android 系统中递归地完成它。我认为我必须以有限的方式使用 sed 和 bash。

如有任何帮助,我们将不胜感激。

编辑: 所以我忘了补充一点,我需要按照下面的方式在文件中每一行的开头和结尾添加行,但是通过上面的更改我需要。

LOG_FILE=/local/log.log;
tmp1="cp"
tmp2=tmp
tmp3=test
for f in /system/*; do [[ -d "$f" ]] || echo $tmp1 $tmp2/$tmp3"$f" "$f"| tee -a $LOG_FILE; done

所以它会像这样输出,/system/file.txt 是我需要复制的路径(用“$f”表示):

cp tmp/test/system/file.txt system/file.txt
cp tmp/test/system/file2.txt system/file2.txt

这应该适用于目录:

find /system/ -type d -print > $LOG_FILE

这应该会为您提供文件列表:

find /system/ -type f -print > $LOG_FILE

要在行首和行尾添加文本,请将 xargs 与 find

find /system/ -type f|xargs -i echo "BEGIN" {} "END" > $LOG_FILE

更新:

#¡/bin/bash

LOG_FILE="log"
tmp1="cp"
tmp2=tmp
tmp3=test

for i in `find /system/ -type f`;
do
  [[ -d "$i" ]] || echo $tmp1 $tmp2/$tmp3"$i" "$i"| tee -a $LOG_FILE;  
done

输出是

cp tmp/test/dir/file dir/file

您可以一次遍历文件和目录的目录:

find . \( -type d -printf "%p\n" \) -o \( -type f -printf  "cp %p tmp/test/%p\n" \) >out.log

并使用不同的 c-style output format directives 来自定义输出。

后面的班轮从起点一层一层走到最深处

let d=1; continue=0; while [[ $continue -eq 0 ]]; do find <start path> -mindepth $d -maxdepth $d -type f -exec echo "<Your message> {}" \; | grep . ; continue=$? ;(( d++ ));  done;

取决于您的需要,您可以在 -type f-type d

之间选择

听起来你有很多处理工作要做,如果我是你,我会使用 find 来获取文件列表及其类型:

$ find tmp -printf '%y %p\n'
d tmp
f tmp/file001
f tmp/file002
f tmp/file003
d tmp/foo
f tmp/foo/file004

然后你可以随心所欲地做任何事,例如:

$ find tmp -printf '%y %p\n' | awk '=="d"{sub(/^../,"");print}'
tmp
tmp/foo

$ find tmp -printf '%y %p\n' | awk '=="f"{sub(/^../,"");print}'
tmp/file001
tmp/file002
tmp/file003
tmp/foo/file004

$ find tmp -printf '%y %p\n' | awk -F'/' '{print NF, [=11=]}' | sort -k1,1n | cut -d' ' -f2-
d tmp
d tmp/foo
f tmp/file001
f tmp/file002
f tmp/file003
f tmp/foo/file004

$ find tmp -printf '%y %p\n' | awk -F'/' '{print NF, [=11=]}' | sort -k1,1nr | cut -d' ' -f2-
f tmp/foo/file004
d tmp/foo
f tmp/file001
f tmp/file002
f tmp/file003
d tmp

您无法从示例中真正看到它,但最后的命令按深度排序。

如果文件名中包含换行符,上述所有操作都会失败。