Bash: 将命令的输出存储到数组中,以 \n 为分隔符

Bash: Store Output of Command to Array with \n as delimiter

我有这样的输出:

dn: CN=XXX XXX,OU=XXX,OU=XXX,O=XXX
cn: XXX XXX
telephonenumber: 1234

dn: CN=XXX XXX,OU=XXX,OU=XXX,O=XXX
cn: XXX XXX
telephonenumber: 1090

dn: CN=XXX XXX,OU=XXX,OU=XXX,O=XXX
cn: XXX XXX
telephonenumber: 1012

我通过一个简单的 ldapsearch 命令得到了这个输出。 我想将这个输出存储在一个数组中,这样我就可以 echo 一个索引并获得一个像

这样的 ldap 条目
echo ${ldaparray[1]}

dn: CN=XXX XXX,OU=XXX,OU=XXX,O=XXX
cn: XXX XXX
telephonenumber: 1090

所以我猜数组定界符将是一个空的新行。

您不必将其存储在数组中,但可以使用以下脚本获取第 i 个条目。

用法:

./print_index.sh filename index

例如,要打印文件 sample.txt 中的第二个条目,请使用

 
./print_index.sh sample.txt 2</p>

FILE=
INDEX=

LINE_NUMBER=`cat $FILE| grep -n "telephonenumber"| awk -F':' {'print '}| head -$INDEX| tail -1`

head -$LINE_NUMBER $FILE| tail -3

这是在 awk 的帮助下构建数组的一种方法:

ldaparray=()
while IFS='' read -d '' -r record; do
    ldaparray+=( "$record" )
done < <(awk -v RS= -v ORS='[=10=]' '1' file)

RS 设置为空字符串会使 awk 将每个文本块视为单独的记录。 1 始终为真,因此打印每条记录,由空字节 ORS 分隔。

循环读取每条记录并向数组添加一个值。

如果您想使用命令的输出而不是文件的内容,请将 <(awk ... file) 更改为 <(command | awk ...)

您可以通过迭代行来构造数组,例如:

# Current index of the array
i=0

# For every line of input (so ignoring '\n's)
while read line; do
    # If the line is empty, then we write in the next array spot
    if test "$line" = ""; then
        i=$(($i+1))
        continue
    fi
    # If this spot already contains some lines,
    # then we concatenate a '\n' then our current line to the array spot
    if test "${ldaparray[$i]}" != ""; then
        ldaparray[$i]="${ldaparray[$i]}\n$line"
    # else no need for a '\n'
    else
        ldaparray[$i]="$line"
    fi
done < <(ldapsearch ...)