如何在bash中迭代包含空格的列表 [英] How to iterate over list which contains whitespaces in bash

查看:31
本文介绍了如何在bash中迭代包含空格的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我如何遍历列表中可以包含空格的项目吗?

Could you please tell me how to iterate over list where items can contain whitespaces?

x=("some word", "other word", "third word")
for word in $x ; do
    echo -e "$word
"
done

如何强制它输出:

some word
other word
third word

代替:

some
word
(...)
third
word

推荐答案

要正确循环项目,您需要使用 ${var[@]}.并且您需要引用它以确保带有空格的项目不被拆分:"${var[@]}".

To loop through items properly you need to use ${var[@]}. And you need to quote it to make sure that the items with spaces are not split: "${var[@]}".

一起:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  echo -e "$word
"
done

或者,更理智(谢谢Charles Duffy) 和 printf:

Or, saner (thanks Charles Duffy) with printf:

x=("some word" "other word" "third word")
for word in "${x[@]}" ; do
  printf '%s

' "$word"
done

这篇关于如何在bash中迭代包含空格的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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