Bash 脚本 - 在变量中存储没有空格的查找命令输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14248039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:10:00  来源:igfitidea点击:

Bash Script - store find command output without spaces in variable

bash

提问by Vebz

I am looking to automate my xcode projects. It all works fine except the projects name with spaces. I have tried the following commands:

我正在寻找自动化我的 xcode 项目。除了带空格的项目名称外,一切正常。我尝试了以下命令:

output_apps=`find ./ -name "*.app" -print`
output_apps=`find ./ -name "*.app"`

When I run

当我跑

find ./ -name "*.app" -print 

without storing into variable, it gives me output as expected as mentioned below:

没有存储到变量中,它给了我预期的输出,如下所述:

.//Ten EU.app
.//Ten Official App EU.app
.//Ten Official App.app
.//Ten.app

However when I store the output of above command in a variable as below

但是,当我将上述命令的输出存储在如下变量中时

output_apps=`find ./ -name "*.app" -print`

and then run the following for loop for get the names

然后运行以下 for 循环以获取名称

for curr_app in $o
do 
    echo "$curr_app"
done

It shows

表明

.//Ten
EU.app
.//Ten
Official
App
EU.app
.//Ten
Official
App.app
.//Ten.app

How do I maintain the spaces between each output and get the following output?

如何维护每个输出之间的空格并获得以下输出?

Ten EU.app
Ten Official App EU.app
Ten Official App.app
Ten.app

回答by Olaf Dietsche

If you don't need to store the file names in a variable, you can use find -print0in combination with xargs -0. This separates the found entries by NUL bytes instead of newlines. xargsreads these NUL separated values and calls some command with as many arguments as possible.

如果不需要将文件名存储在变量中,则可以find -print0xargs -0. 这将通过 NUL 字节而不是换行符分隔找到的条目。xargs读取这些 NUL 分隔值并调用一些带有尽可能多参数的命令。

find ./ -name "*.app" -print0 | xargs -0 some-command

If you want, you can limit the number of arguments given to some-commandwith xargs -n 1

如果你愿意,你可以限制给参数的个数some-commandxargs -n 1

find ./ -name "*.app" -print0 | xargs -0 -n 1 some-command

Yet another approach is to read the files with a whileloop

另一种方法是用while循环读取文件

find ./ -name "*.app" -print | while read f; do
    some-command "$f"
done

This calls some command with one file at a time. The important point is to enclose the $finto double quotes.

这一次用一个文件调用一些命令。最重要的一点是要封闭$f双引号

回答by alinsoar

The file names may contain spaces. You need to ask find to separate them via NULL(\0). Use find -print0.

文件名可能包含空格。您需要通过 find 将它们分开NULL(\0)。使用find -print0.