将Bash数组转换为分隔的字符串

问题描述 投票:28回答:3

我想知道以下内容;

  1. 为什么给定的非工作示例不起作用。
  2. 如果有任何其他清洁方法,而不是工作示例中给出的方法。

非工作的例子

> ids=(1 2 3 4);echo ${ids[*]// /|}
1 2 3 4
> ids=(1 2 3 4);echo ${${ids[*]}// /|}
-bash: ${${ids[*]}// /|}: bad substitution
> ids=(1 2 3 4);echo ${"${ids[*]}"// /|}
-bash: ${"${ids[*]}"// /|}: bad substitution

工作实例

> ids=(1 2 3 4);id="${ids[@]}";echo ${id// /|}
1|2|3|4
> ids=(1 2 3 4); lst=$( IFS='|'; echo "${ids[*]}" ); echo $lst
1|2|3|4

在上下文中,用于sed命令的分隔字符串用于进一步解析。

arrays string bash delimited-text
3个回答
30
投票
# REVISION: 2017-03-14
# Use of read and other bash specific features (bashisms)

因为括号用于分隔数组,而不是字符串:

ids="1 2 3 4";echo ${ids// /|}
1|2|3|4

一些样本:用两个字符串填充$idsa bc d

ids=("a b" "c d")

echo ${ids[*]// /|}
a|b c|d

IFS='|';echo "${ids[*]}";IFS=$' \t\n'
a b|c d

......最后:

IFS='|';echo "${ids[*]// /|}";IFS=$' \t\n'
a|b|c|d

组装数组时,由$IFS的第一个字符分隔,但在数组的每个元素中用|替换空格。

当你这样做时:

id="${ids[@]}"

您将字符串构建从数组ids合并空格转换为字符串类型的新变量。

注意:当"${ids[@]}"给出一个以空格分隔的字符串时,"${ids[*]}"(使用星号*而不是at符号@)将呈现由$IFS的第一个字符分隔的字符串。

什么man bash说:

man -Len -Pcol\ -b bash | sed -ne '/^ *IFS /{N;N;p;q}'
   IFS    The  Internal  Field  Separator  that  is used for word splitting
          after expansion and to split  lines  into  words  with  the  read
          builtin command.  The default value is ``<space><tab><newline>''.

$IFS一起玩:

set | grep ^IFS=
IFS=$' \t\n'

declare -p IFS
declare -- IFS=" 
"
printf "%q\n" "$IFS"
$' \t\n'

字面意思是spacetabulation和(意思或)line-feed。所以,虽然第一个角色是一个空间。使用*将与@一样。

但:

{

    # OIFS="$IFS"
    # IFS=$': \t\n'
    # unset array 
    # declare -a array=($(echo root:x:0:0:root:/root:/bin/bash))

    IFS=: read -a array < <(echo root:x:0:0:root:/root:/bin/bash)

    echo 1 "${array[@]}"
    echo 2 "${array[*]}"
    OIFS="$IFS" IFS=:
    echo 3 "${array[@]}"
    echo 4 "${array[*]}"
    IFS="$OIFS"
}
1 root x 0 0 root /root /bin/bash
2 root x 0 0 root /root /bin/bash
3 root x 0 0 root /root /bin/bash
4 root:x:0:0:root:/root:/bin/bash

注意:行IFS=: read -a array < <(...)将使用:作为分隔符,而不会永久设置$IFS。这是因为输出线#2将空格显示为分隔符。


12
投票

你的第一个问题已在F. Hauri's answer中得到解决。这是加入数组元素的规范方法:

ids=( 1 2 3 4 )
IFS=\| eval 'lst="${ids[*]}"'

有些人会大声喊叫eval是邪恶的,但由于单引号,这里非常安全。这只有一个优点:没有子shell,IFS没有全局修改,它不会修剪尾随换行符,而且非常简单。


4
投票

您也可以使用printf,无需任何外部命令或需要操作IFS:

ids=(1 2 3 4)                     # create array
printf -v ids_d '|%s' "${ids[@]}" # yields "|1|2|3|4"
ids_d=${ids_d:1}                  # remove the leading '|'

0
投票

用于使用分隔符字符串拆分自变量数组的实用程序函数:

# Split arguments on delimiter
# @Params
# $1: The delimiter string
# $@: The arguments to delimit
# @Output
# >&1: The arguments separated by the delimiter string
split() {
  (($#<2)) && return 1 # At least 2 arguments required
  local -- delim="$1" str
  shift
  printf -v str "%s$delim" "$@"
  echo "${str:0:-${#delim}}"
}

my_array=( 'Paris' 'Berlin' 'London' 'Brussel' 'Madrid' 'Oslo' )

split ', ' "${my_array[@]}"

输出:

Paris, Berlin, London, Brussel, Madrid, Oslo
© www.soinside.com 2019 - 2024. All rights reserved.