【问题标题】:Looping through find output in Bash where file name contains white spaces在 Bash 中循环查找输出,其中文件名包含空格
【发布时间】:2012-07-07 03:32:26
【问题描述】:

我尝试搜索可能包含空格的文件我尝试使用-print0 并设置IFS 这是我的脚本

IFS=$'\0';find people -name '*.svg' -print0 | while read file; do
    grep '<image' $file > /dev/null && echo $file | tee -a embeded_images.txt;
done

我尝试对所有包含嵌入图像的 svg 文件进行精细处理,它在没有 -print0 的情况下工作,但一个文件失败,所以我停止了脚本。这是一个更简单的例子,但也不起作用

IFS=$'\0';find . -print0 | while read file; do echo $file; done

它什么都不显示。

【问题讨论】:

    标签: bash find while-loop


    【解决方案1】:

    使用read -d '' -r file 并仅为read 的上下文设置IFS

    find people -name '*.svg' -print0 | while IFS= read -d '' -r file; do
        grep '<image' "$file" > /dev/null && echo "$file" | tee -a embeded_images.txt;
    done
    

    并引用你的变量。

    【讨论】:

    • @IFS= read@ 方法对以空格结尾的文件成功
    • 奇怪的read -d'' -r file; do 不起作用,但空格-d '' 可以。
    • @jcubic:单引号的内容为空。 Bash 将-d'' 视为一个论点。当它确实引用删除时,除了-d,什么都没有了。它将-d '' 视为两个 参数,其中一个为空。
    【解决方案2】:

    虽然Dennis Williamson's answer 绝对正确,但creates a subshell 会阻止您在循环内设置任何变量。您可以考虑使用进程替换,如下所示:

    while IFS= read -d '' -r file; do
        grep '<image' "$file" > /dev/null && echo "$file" | tee -a embeded_images.txt
    done < <(find people -name '*.svg' -print0)
    

    第一个&lt; 表示您正在从文件中读取,&lt;(find...) 被替换为直接从find 返回输出的文件名(通常是管道句柄)。因为while 从文件而不是管道读取,所以您的循环可以设置可从范围外访问的变量。

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2018-06-01
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2015-02-02
      相关资源
      最近更新 更多