linux - Bash - 如何使用 find 命令排除目录以及如何使用 find 获取完整路径?

标签 linux bash shell unix

所以我现在有下面的代码,但我遇到了一些问题

  1. 我无法排除

    输出的目录
    find ${1-.}
    

    它也给了我目录,而不仅仅是名字;我尝试了不同的方法,例如 -prune 等。

  2. 我在删除空文件时遇到问题

给我的数据

    EMPTY_FILE=$(find ${1-.} -size 0)

没有给我正确的路径 这是它的输出

    TestFolder/TestFile

在这种情况下我不能只做:

    rm TestFolder/TestFile

因为它是无效的路径;因为它需要 ./TestFolder/TestFile

我将如何在 ./上添加或在那里获取完整路径。

    #!/bin/bash

    echo "Here are all the files in the directory specified\n"
    find ${1-.}

    EMPTY_FILE=$(find ${1-.} -size 0)
    echo "Here are the list of empty files\n"
    echo "$EMPTY_FILE \n"
    echo "Do you want to delete those empty files?(yes/no)"
    read text
    if [ "$text" == "yes" ]; then $(rm -- $EMPTY_FILE); fi

感谢任何帮助!

最佳答案

你想要这个:

#!/bin/bash

echo -e "Here are all the files in the directory specified\n"

# Use -printf "%f\n" to print the filename without leading directories
# Use -type f to restrict find to files
find "${1-.}" -type f -printf "    %f\n"

echo -e "Here are the list of empty files\n"

# Again, use -printf "%f\n"
find "${1-.}" -type f -size 0 -printf "    %f\n"

echo -e "Do you want to delete those empty files?(yes/no)"
read answer

# Delete files using the `-delete` option
[ "$answer" = "yes" ] && find "${1-.}" -type f -size 0 -delete

另请注意,我在所有出现的地方都引用了 "${1-.}"。由于它是用户输入,因此您不能依赖输入。即使它是一条路径,它仍可能包含有问题的字符,例如空格。

关于linux - Bash - 如何使用 find 命令排除目录以及如何使用 find 获取完整路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35069942/

相关文章:

shell - 如何在 mongodb 函数中执行 mongodb 查询?

java - 如何从 Java 运行 shell 脚本并让它在 JVM 关闭后继续运行?

Linux,如何在表中共享相同列值的行?

linux - 用于迁移配置文件变量的 Shell 脚本

bash - logrotate:即使日志没有旋转,你也可以运行 postrotate 吗?

c - 如何用C语言创建一个可以实现向上箭头历史捕获的shell?

java - 使用 shell 在 Jenkins master 上运行 Selenium Java 代码

linux - 设置Linux权限以防止其他用户删除/修改文件

linux - 如何在 Linux 上启用 WiFi channel 12 和 13?

linux - 如何使用 sudo 将环境变量导出到后台进程运行?