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

时间:2016-08-04 10:05:15

标签: 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

2 个答案:

答案 0 :(得分:5)

请勿以find语法循环for i in $(find . -type f)命令,请参阅Bash Pit-falls 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.

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

#!/bin/bash

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

    # Your script goes here

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

答案 1 :(得分:0)

只需将IFS更改为非空格(在那里找到:How to loop through file names returned by find? ):

IFS="\r\n"

Alsol Lame(但有效)只是在空间字符上添加了一个sed过滤器/未过滤器

for ix in $( find "." -maxdepth 1 -mindepth 1 -type d | sed "s/ /%SPC%/g"); do
    i=$(echo "$ix" | sed "s/%SPC%/ /g")
    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