加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash“for in”循环空定界字符串变量

发布时间:2020-12-15 20:05:45 所属栏目:安全 来源:网络整理
导读:我想迭代通过文件列表而不关心文件名可能包含什么字符,所以我使用由空字符分隔的列表。代码将解释更好的东西。 # Set IFS to the null character to hopefully change the for..in# delimiter from the space character (sadly does not appear to work).IF
我想迭代通过文件列表而不关心文件名可能包含什么字符,所以我使用由空字符分隔的列表。代码将解释更好的东西。
# Set IFS to the null character to hopefully change the for..in
# delimiter from the space character (sadly does not appear to work).
IFS=$''

# 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 $'' 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读