0

I have Output like that:

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

I get this output from a simple ldapsearch command. I want to store this output in an array so that i can echo an index and get one ldap entry like

echo ${ldaparray[1]}

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

So I to array delimiter would be an empty new line I guess.

JMAD2016
  • 111
  • 1
  • 2
  • 9
  • Possible duplicate of [How do I assign the output of a command into an array?](http://stackoverflow.com/questions/9449417/how-do-i-assign-the-output-of-a-command-into-an-array) – Julien Lopez Dec 05 '16 at 11:56
  • 1
    @JulienLopez looks good. But how is the IFS for an empty new line? with $='\n' he splits every new line to an index – JMAD2016 Dec 05 '16 at 12:02
  • Whoops, you're right, sorry. You may need to use awk or a loop on this one. – Julien Lopez Dec 05 '16 at 12:22

3 Answers3

1

Here's one way to build your array, with some help from awk:

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

Setting RS to the empty string makes awk treat each block of text as a separate record. 1 is always true, so each record is printed, separated by the ORS, a null byte.

The loop reads each of these records and adds a value to the array.

Change <(awk ... file) to <(command | awk ...), if you want to work with the output of a command, rather than the contents of a file.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

You do not have to store it in an array but can use the below script to get the i'th entry.

Usage:

./print_index.sh filename index

Example, to print the second entry from file sample.txt use

 
./print_index.sh sample.txt 2

FILE=$1
INDEX=$2

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

head -$LINE_NUMBER $FILE| tail -3

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
Sh00nya
  • 71
  • 1
  • 2
0

You can construct your array by iterating on the lines, for example:

# 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 ...)
Julien Lopez
  • 1,794
  • 5
  • 18
  • 24