加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 19:03:53 所属栏目:安全 来源:网络整理
导读:我想知道以下内容; 为什么给定的非工作示例不起作用。 如果有任何其他清洁方法,而不是工作示例中给出的方法。 非工作的例子 ids=(1 2 3 4);echo ${ids[*]// /|}1 2 3 4 ids=(1 2 3 4);echo ${${ids[*]}// /|}-bash: ${${ids[*]}// /|}: bad substitution id
我想知道以下内容;

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

非工作的例子

> 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命令的分隔字符串用于进一步解析。

# REVISION: 2017-03-14
# Use of read and other bash specific features (bashisms)

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

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

一些示例:用两个字符串填充$ id:a b和c d

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

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

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

……最后:

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

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

当你这样做时:

id="${ids[@]}"

您将字符串构建从数组ID的空间合并传输到字符串类型的新变量。

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

什么人打击说:

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=$' tn'
declare -p IFS
declare -- IFS=" 
"
printf "%qn" "$IFS"
$' tn'

字面意思是空格,制表和(意义或)换行。所以,虽然第一个角色是一个空间。使用*将与@相同。

但:

{
# OIFS="$IFS"
    # IFS=$': tn'
    # 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将空格作为分隔符。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读