【问题标题】:How preserve space separated groups in bash如何在 bash 中保留空格分隔的组
【发布时间】:2016-11-03 14:41:45
【问题描述】:

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

# 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 数组有一个问题,它们不能通过传送带传输 -(回声/$())。

【问题讨论】:

  • 当然不是。如果它可能的,那么就不需要数组了。

标签: string bash


【解决方案1】:

一种肮脏的方法是:

#!/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

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


旁注

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

【讨论】:

    猜你喜欢
    • 2019-11-02
    • 1970-01-01
    • 2023-03-15
    • 2019-09-16
    • 2018-11-19
    • 1970-01-01
    • 2014-01-13
    • 2023-04-01
    • 2013-06-02
    相关资源
    最近更新 更多