gpt4 book ai didi

bash - 在 bash 脚本中使用 find 命令

转载 作者:行者123 更新时间:2023-11-29 08:43:48 24 4
gpt4 key购买 nike

我刚开始使用 bash 脚本,我需要对不止一种文件类型使用 find 命令。

list=$(find /home/user/Desktop -name '*.pdf') 

此代码适用于 pdf 类型,但我想一起搜索不止一种文件类型,如 .txt 或 .bmp。你有什么想法吗?

最佳答案

欢迎使用 bash。这是一个古老、黑暗和神秘的东西,具有强大的魔法。 :-)

不过,您要询问的选项是针对 find 命令的,而不是针对 bash 的。在命令行中,您可以man find 来查看选项。

你要找的是 -o for "or":

  list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"

就是说......不要这样做。这样的存储可能适用于简单的文件名,但一旦你必须处理特殊字符,比如空格和换行符,所有赌注都关闭了。参见 ParsingLs了解详情。

$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt

路径名扩展(通配)提供了一种更好/更安全的方式来跟踪文件。然后你也可以使用 bash 数组:

$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 one.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 two three.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 foo.bmp

Bash FAQ还有很多其他关于 bash 编程的优秀技巧。

关于bash - 在 bash 脚本中使用 find 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com