Reputation: 121
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.
Upvotes: 0
Views: 951
Reputation: 74596
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.
Upvotes: 1
Reputation: 1844
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 ...)
Upvotes: 0
Reputation: 81
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
Upvotes: 0