linux - 如何修复 Linux bash 的 'find' 命令中包含空格的路径

标签 linux bash unix

<分区>

我必须在 Linux 中使用包含空格字符的路径, 我的以下命令适用于非空格路径,但如果路径包含空格,它将失败。

#!/bin/bash
for i in $( find "." -maxdepth 1 -mindepth 1 -type d ); do
    b=$(echo "$i" | awk '{print substr($1,3); }' )
    echo "This file contain <Modified date> <ActualSize Byte>   <FullPath>" > "$i"/"$b".txt
    find "$i" -type f ! -iname '*thumbs.db*' -print0 | xargs -0 stat -c "%y %s %n" >> "$i"/"$b".txt
done

这是我的文件夹列表。

.
./Folder 1
./Folder 2
./Folder 3

脚本错误如下。

./xyz.sh: line 4: ./Folder/Folder.txt: No such file or directory
find: ./Folder: No such file or directory
./xyz.sh: line 5: ./Folder/Folder.txt: No such file or directory
./xyz.sh: line 4: 1/.txt: No such file or directory
find: 1: No such file or directory
./xyz.sh: line 5: 1/.txt: No such file or directory
./xyz.sh: line 4: ./Folder/Folder.txt: No such file or directory
find: ./Folder: No such file or directory
./xyz.sh: line 5: ./Folder/Folder.txt: No such file or directory
./xyz.sh: line 4: 2/.txt: No such file or directory
find: 2: No such file or directory
./xyz.sh: line 5: 2/.txt: No such file or directory
./xyz.sh: line 4: ./Folder/Folder.txt: No such file or directory
find: ./Folder: No such file or directory
./xyz.sh: line 5: ./Folder/Folder.txt: No such file or directory
./xyz.sh: line 4: 3/.txt: No such file or directory
find: 3: No such file or directory
./xyz.sh: line 5: 3/.txt: No such file or directory

最佳答案

不要将 find 命令作为 for i in $(find . -type f) 语法循环,参见 Bash Pit-falls使用 find-print0,在 while 循环中保留文件夹/文件名上的特殊字符,如下所示:-

查看 findman 页面关于 -print0 选项的内容:-

   -print0
          True; print the full file name on the standard output, followed by
          a null character (instead of the newline character that -print
          uses).  This allows file names  that  contain newlines or other
          types of white space to be correctly interpreted by programs that
          process the find output.  This option corresponds to the -0 option 
          of xargs.

在脚本中使用相同的内容,如下所示。

#!/bin/bash

while IFS= read -r -d '' folder; do

    # Your script goes here

done < <(find . -maxdepth 1 -mindepth 1 -type d -print0)

关于linux - 如何修复 Linux bash 的 'find' 命令中包含空格的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38764326/

相关文章:

c - MPI 如何决定我们创建多少个进程

c - readdir_r 进入长文件名的无限循环

linux - 关于 c/c++ [ubuntu] gnome 或 kde 中的鼠标控制???大概

bash - 导出 xtrace/BASH_XTRACEFD 但 xtrace 输出将发送到 stderr,而不是自定义文件描述符

bash - 从名称获取 AWS EMR 集群 ID

bash awk 整数

linux - 在 Bash 脚本中创建日志

linux - 如何使用 shell 脚本查找具有最大上下文长度的行号?

linux - 如何在 linux bash shell 中对字符串数组进行排序?

linux - 我是否需要为并发下载设置下载速度限制(使用 cURL),或者它们将平分?