前端之家收集整理的这篇文章主要介绍了
bash“for in”循环空定界字符串变量,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
403_0@
我想迭代通过
文件列表而不关心
文件名可能包含什么字符,所以我使用由空字符分隔的列表。
代码将解释更好的东西。
# 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
谢谢!
在bash中,你可以使用here-string
while IFS= read -r -d '' line ; do
# Code here
done <<<"$var"
注意,你应该内联IFS =,只是使用-d“’,但确保’d’和第一个单引号之间有一个空格。另外,添加-r标志以忽略转义。
此外,这不是你的问题的一部分,但我可以建议一个更好的方式来做你的脚本,当使用find;它使用过程替换。
while IFS= read -r -d '' file; do
# Arbitrary operations on "$file" here
done < <(find /some/path -type f -print0)