首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >循环遍历文件名包含空格的Bash中的find输出

循环遍历文件名包含空格的Bash中的find输出
EN

Stack Overflow用户
提问于 2012-07-07 00:30:21
回答 2查看 14.6K关注 0票数 19

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

代码语言:javascript
复制
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的情况下工作,但有一个文件失败了,所以我停止了脚本。这里有一个更简单的例子,它也不起作用

代码语言:javascript
复制
IFS=$'\0';find . -print0 | while read file; do echo $file; done

它不会显示任何内容。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-07 00:34:41

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

代码语言:javascript
复制
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

引用你的变量。

票数 27
EN

Stack Overflow用户

发布于 2014-05-20 07:16:32

虽然Dennis Williamson's answer是绝对正确的,但它是creates a subshell,这将阻止您在循环中设置任何变量。您可以考虑使用进程替换,因此:

代码语言:javascript
复制
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)

第一个<表示您正在从文件中读取数据,并且<(find...)被替换为直接从find返回输出的文件名(通常是管道的句柄)。因为while读取的是文件而不是管道,所以您的循环可以设置可从作用域外部访问的变量。

票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11366184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档