通过查找返回的字符串被中间分开 [英] strings returned by find gets separated in the middle

查看:101
本文介绍了通过查找返回的字符串被中间分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的外壳(bash)的脚本。在终端,找到表现为:

I'm new to shell (bash) script. On terminal, find behaves as:

find . -name 'Ado*'
./Adobe ReaderScreenSnapz001.jpg
./Adobe ReaderScreenSnapz002.jpg

不过,我的shell脚本仿佛为Adobe。

However, my shell script seems to separate the file name by the space after "Adobe".

code:

#!/bin/sh
i=1
for base_name in `find . -name "Ado*"`
do
echo $base_name
 :
i=$((i+1))
done

它返回是这样的:

It returns something like:

./Adobe
ReaderScreenSnapz001.jpg
 :

什么是错在何处?

What's wrong where?

推荐答案

大多数的答案到目前为止已经使用的发现... |而读... 这工作,但while循环在子shell中运行(因为它是一个管道的一部分),所以你的文件(I $)的计数时,会丢失子shell退出。如果你正在使用bash(即你的家当的必须的是#!/斌/庆典,而不是#!/ bin中/ SH ),你可以使用它的过程中替换功能来避免这个问题:

Most of the answers so far have used find ... | while read ... which works, but the while loop runs in a subshell (because it's part of a pipeline), and so your count of files ($i) is lost when the subshell exits. If you're using bash (i.e. your shebang must be #!/bin/bash, not #!/bin/sh), you can use its process substitution feature to avoid this problem:

i=1
while IFS= read -r -u3 -d '' base_name; do
    echo "$base_name"
    :
    i=$((i+1))
done 3< <(find . -name "Ado*" -print0)

我还添加了一些其他的技巧在这里,使这个更强大的:我设置IFS为空(只为读命令),所以它不会修剪引导或文件名结尾的空白;我用读的 -r 选项,这样就不会做在文件名中的反斜杠有趣的事情;我用查找的 -print0 和阅读的 -d''使用空字节作为文件分隔符,所以它赢得了吨甚至在文件名换行符相混淆;我周围使用 $ BASE_NAME 双引号内循环,所以它不会对空白得到拆分有两种(不适用于回声很重要,但它会没关系,如果你真的尝试使用文件名作为文件名);最后,我通过通过FD#3,而不是#0(标准输入)文件列表用 3'; 和阅读的 -u3 选项,这样在任何情况下,内循环从标准会不小心吸入了一堆文件名的读取。

I've also added some other tricks here to make this more robust: I set IFS to null (just for the read command) so it won't trim leading or trailing whitespace from filenames; I use read's -r option so it won't do funny things with backslashes in filenames; I use find's -print0 and read's -d '' to use null bytes as the file delimiter, so it won't even be confused by linefeeds in filenames; I use double-quotes around $base_name inside the loop, so it won't get split on whitespace there either (not important for echo, but it'll matter if you actually try to use the filenames as filenames); finally, I pass the file list via fd #3 instead of #0 (stdin) with 3< and read's -u3 option, so in case anything inside the loop reads from stdin it won't accidentally inhale a pile of filenames.

这篇关于通过查找返回的字符串被中间分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆