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

NNO*_*OPP 0 unix linux bash

我必须在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
Run Code Online (Sandbox Code Playgroud)

这是我的文件夹列表.

.
./Folder 1
./Folder 2
./Folder 3
Run Code Online (Sandbox Code Playgroud)

脚本的错误如下.

./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
Run Code Online (Sandbox Code Playgroud)

Ini*_*ian 5

不要遍历find命令for i in $(find . -type f)语法,请参阅击坑瀑布使用find-print0,对一个while循环,如下保存在文件夹/文件名的特殊字符: -

看看关于该选项的man页面: -find-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.
Run Code Online (Sandbox Code Playgroud)

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

#!/bin/bash

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

    # Your script goes here

done < <(find . -maxdepth 1 -mindepth 1 -type d -print0)
Run Code Online (Sandbox Code Playgroud)