bash - 字段分隔符空格或换行符

时间:2018-01-08 09:50:16

标签: bash

我喜欢从stdin循环数据。这样的事情:

03-02-01-00-05-04-07-06-08-09-0A-0B-0C-0D-0E-0F

但是我无法预测我的输入数据是用空格还是换行符分隔的。有什么想法怎么做?没有产生新的过程高度赞赏。

3 个答案:

答案 0 :(得分:4)

这不是特别优雅或高效,但它确实满足仅使用shell内部功能的要求。

while read -r line; do
    for word in $line; do
        blah blah blah "$word"
    done
done

使用不带引号的$line不仅要使空格标记化值,还要使用通配符扩展;如果你想避免这种情况,the noglob option是你的朋友,虽然在你的脚本中打开和关闭它是一个巨大的麻烦,如果你需要通过其他部分工作 - 可能花费一个外部过程是一个小问题然后

答案 1 :(得分:3)

我的努力类似于@ 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[*]}"非常重要。

编辑:Re。上面的注释,忽略制表符作为分隔符:

while IFS=$'\n ' read -r -a items

答案 2 :(得分:0)

您可以使用tr:

将所有空格转换为换行符
tr ' ' '\n'
相关问题