如何循环包含在bash空格名单 [英] How to iterate over list which contains whitespaces in bash

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

问题描述

你能告诉我怎么遍历列表,项目可以包含空格?

  X =(一些词,其他字,第三个字)
在$ X字;做
    回声-e$字\\ n
DONE

如何迫使它输出:

 一些字
换句话说
第三个单词

而不是:

 部分

(......)
第三


解决方案

要遍历项目正常,你需要使用 $ {VAR [@]} 。而你需要引用它,以确保与空间的项目不拆:$ {VAR [@]}

总之:

  X =(一些词等字,第三个字)
在Word$ {X [@]};做
  回声-e$字\\ n
DONE

或者,更加理智(<一个href=\"http://stackoverflow.com/questions/14587972/how-to-iterate-over-list-which-contains-whitespaces-in-bash/14588210#comment48184385_14588210\">thanks查尔斯·达菲)与的printf

  X =(一些词等字,第三个字)
在Word$ {X [@]};做
  printf的'%s的\\ n \\ n'$词
DONE

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\n"
done

how to force it to output:

some word
other word
third word

instead of:

some
word
(...)
third
word

解决方案

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[@]}".

All together:

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

Or, saner (thanks Charles Duffy) with printf:

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

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

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