如何在bash中保留空格分隔的组

时间:2016-07-01 08:54:31

标签: string bash

我想构建一个包含引用词组的字符串。 这些组应该转到相同的函数参数。 我试着玩数组。 字面构造的数组工作,但我仍然希望找到 一个神奇的语法破解裸字符串。

# literal array
LA=(a "b c")

function printArgs() { # function should print 2 lines
  while [ $# -ne 0 ] ; do print $1 ; shift; done
}

printArgs "${LA[@]}" # works fine
# but how to use string to split only unquoted spaces?

LA="a \"b c\""
printArgs "${LA[@]}" # doesn't work :(
LA=($LA)
printArgs "${LA[@]}" # also doesn't work :(

bash数组有一个问题,它们不能通过传送带传输 - (echo / $())。

1 个答案:

答案 0 :(得分:0)

一种肮脏的方法是:

#!/bin/bash
LA=(a "b  c")

function printArgs()
{ # function should print 2 lines
  while [ $# -ne 0 ]
  do
   echo "${1//_/ }" #Use parameter expansion to globally replace '_' with space
  #Do double quote as we don't want to have word splitting
   shift
  done
}

printArgs "${LA[@]}" # works fine

LA="a b__c" # Use a place holder '_' for space, note the two '_' for two spaces
printArgs $LA #Don't double quote '$LA' here. We wish word splitting to happen. And works fine :-)

示例输出

a
b  c
a
b  c

请注意,保留分组实体内的空格数

<强>旁注

占位符的选择在这里至关重要。希望你能找到一个不会出现在实际字符串中的字符。