通过Bash循环读取以空分隔的字符串 [英] Reading null delimited strings through a Bash loop

查看:99
本文介绍了通过Bash循环读取以空分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历文件列表,而不关心文件名可能包含哪些字符,因此我使用一个以空字符分隔的列表.该代码将更好地说明问题.

# 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变量,只要不是以NUL终止,您就可以这样做. >

这是bash var包含制表符分隔的字符串的示例

$ var=$(echo -ne "foo\tbar\tbaz\t"); 
$ while IFS= read -r -d $'\t' line ; do \
    echo "#$line#"; \
  done <<<"$var"
#foo#
#bar#
#baz#

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

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

解决方案

The preferred way to do this is using process substitution

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

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

$ var=$(echo -ne "foo\tbar\tbaz\t"); 
$ while IFS= read -r -d $'\t' line ; do \
    echo "#$line#"; \
  done <<<"$var"
#foo#
#bar#
#baz#

这篇关于通过Bash循环读取以空分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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