通过Bash循环读取以空分隔的字符串 [英] Reading null delimited strings through a Bash loop
问题描述
我想遍历文件列表,而不关心文件名可能包含哪些字符,因此我使用一个以空字符分隔的列表.该代码将更好地说明问题.
# 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
从文件读取时,以下代码有效,但我需要从包含文本的变量中读取.
while read -d $'\0' line ; do
# Code here
done < /path/to/inputfile
执行此操作的首选方法是使用进程替换
while IFS= read -r -d $'\0' file; do
# Arbitrary operations on "$file" here
done < <(find /some/path -type f -print0)
如果您以类似的方式来分析bash变量,只要 这是bash var包含制表符分隔的字符串的示例 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. The following code works when reading from a file, but I need to read from a variable containing text.
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 not NUL-terminated. Here is an example of bash var holding a tab-delimited string
这篇关于通过Bash循环读取以空分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!不是以NUL终止,您就可以这样做. >
$ var=$(echo -ne "foo\tbar\tbaz\t");
$ while IFS= read -r -d $'\t' line ; do \
echo "#$line#"; \
done <<<"$var"
#foo#
#bar#
#baz#
# 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
while read -d $'\0' line ; do
# Code here
done < /path/to/inputfile
while IFS= read -r -d $'\0' file; do
# Arbitrary operations on "$file" here
done < <(find /some/path -type f -print0)
$ var=$(echo -ne "foo\tbar\tbaz\t");
$ while IFS= read -r -d $'\t' line ; do \
echo "#$line#"; \
done <<<"$var"
#foo#
#bar#
#baz#