通过 Bash 循环读取空分隔字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8677546/
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
Reading null delimited strings through a Bash loop
提问by Matthew
I want to iterate through a list of files without caring about what characters the filenames might contain, so I use a list delimited by null characters. The code will explain things better.
我想遍历文件列表而不关心文件名可能包含哪些字符,因此我使用由空字符分隔的列表。代码将更好地解释事情。
# Set IFS to the null character to hopefully change the for..in
# delimiter from the space character (sadly does not appear to work).
IFS=$'while read -d $'while IFS= read -r -d $'$ var=$(echo -ne "foo\tbar\tbaz\t");
$ while IFS= read -r -d $'\t' line ; do \
echo "#$line#"; \
done <<<"$var"
#foo#
#bar#
#baz#
' file; do
# Arbitrary operations on "$file" here
done < <(find /some/path -type f -print0)
' line ; do
# Code here
done < /path/to/inputfile
'
# Get null delimited list of files
filelist="`find /some/path -type f -print0`"
# Iterate through list of files
for file in $filelist ; do
# Arbitrary operations on $file here
done
The following code works when reading from a file, but I need to read from a variable containing text.
以下代码在从文件中读取时有效,但我需要从包含文本的变量中读取。
import sh
import path
files = path.Path(".").files()
for x in files:
sh.cp("--reflink=always", x, "UUU00::%s"%(x.basename(),))
sh.cp("--reflink=always", x, "UUU01::%s"%(x.basename(),))
回答by SiegeX
The preferred way to do this is using process substitution
执行此操作的首选方法是使用进程替换
##代码##If you were hell-bent on parsing a bash variable in a similar manner, you can do so as long as the list is notNUL-terminated.
如果您一心想以类似的方式解析 bash 变量,只要列表不是NUL-terminated就可以这样做。
Here is an example of bash var holding a tab-delimited string
这是一个包含制表符分隔字符串的 bash var 示例
##代码##回答by Henry Crutcher
I tried working with the bash examples above, and finally gave up, and used Python, which worked the first time. For me it turned out the problem was simpler outside the shell. I know this is possibly off topic of a bash solution, but I'm posting it here anyway in case others want an alternative.
我尝试使用上面的 bash 示例,最后放弃了,并使用了第一次有效的 Python。对我来说,结果证明问题在外壳之外更简单。我知道这可能与 bash 解决方案无关,但无论如何我都会在这里发布它,以防其他人想要替代方案。
##代码##