庆典"在"在循环空分​​隔字符串变量 [英] bash "for in" looping on null delimited string variable

查看:133
本文介绍了庆典"在"在循环空分​​隔字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过的文件列表进行迭代,而无需关心文件名可能包含哪些字符,所以我用空字符分隔列表。在code将更好地解释的东西。

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=$'\0'

# 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

以下code从文件中读取数据时的作品,但我需要从包含文本变量来阅读。

The following code works when reading from a file, but I need to read from a variable containing text.

while read -d $'\0' line ; do
    # Code here
done < /path/to/inputfile

谢谢!

推荐答案

在bash,那么你可以使用下面的字符串

In bash you can use a here-string

while IFS= read -r -d '' line ; do
    # Code here
done <<<"$var"

请注意,您应内嵌 IFS = ,只使用 -d''但要确保有一个在D和第一个单引号之间的空间。此外,添加了 -r 标志忽略逃逸。

Note that you should inline the IFS= and just use -d '' but make sure there is a space between the 'd' and the first single-quote. Also, add the -r flag to ignore escapes.

此外,这是不是你的问题的一部分,但我可能会建议一个更好的办法时使用找到做你的脚本;它使用进程替换。

Also, this isn't part of your question but might I suggest a better way to do your script when using find; it uses process substitution.

while IFS= read -r -d '' file; do
    # Arbitrary operations on "$file" here
done < <(find /some/path -type f -print0)

这篇关于庆典&QUOT;在&QUOT;在循环空分​​隔字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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