[英]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
所以我想數組定界符將是一個空的新行。
這是一種在awk的幫助下構建數組的方法:
ldaparray=()
while IFS='' read -d '' -r record; do
ldaparray+=( "$record" )
done < <(awk -v RS= -v ORS='\0' '1' file)
將RS
設置為空字符串會使awk將每個文本塊都視為單獨的記錄。 1
始終為真,因此將打印每個記錄,並用ORS
(一個空字節)分隔。
循環讀取這些記錄中的每條記錄,並向數組添加一個值。
如果要使用命令的輸出而不是文件的內容,請將<(awk ... file)
更改為<(command | awk ...)
。
您不必將其存儲在數組中,但可以使用以下腳本獲取第i個條目。
用法:
./print_index.sh filename index
例如,要打印文件sample.txt中的第二個條目,請使用
./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
您可以通過在行上進行迭代來構造數組,例如:
# 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 ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.