[英]BASH printf array with field separator and newline on last entry
[英]bash - field separator space or newline
我想循环来自stdin的数据。 像这样:
while read -r line; do
blah blah blah
done
但是我无法预测我的输入数据是否由空格或换行符分隔。 有什么想法怎么做? 不催生新的过程表示高度赞赏。
这不是特别优雅或有效,但确实满足了仅使用shell内部功能的要求。
while read -r line; do
for word in $line; do
blah blah blah "$word"
done
done
使用不带引号的$line
不仅要对该值进行空格标记化,而且还要对通配符进行扩展。 如果您想避免这种情况, 则noglob
选项是您的朋友,但是如果您需要在其他部分进行工作,则在脚本中打开和关闭它会很麻烦-也许花一个外部进程是一个较小的问题。
我的工作类似于@tripleee的工作,但是没有遇到问题,我使用了数组并引用了扩展名:
while read -r -a items
do
for item in "${items[@]}" # Quotes are important here
do
echo "$item" # blah blah blah
done
done < gash.txt
请注意,使用"${items[@]}"
而不是 "${items[*]}"
。
编辑:重新。 在上面的注释中,忽略制表符作为分隔符:
while IFS=$'\n ' read -r -a items
您可以使用tr将所有空格转换为换行符:
tr ' ' '\n'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.