Skip to content

Instantly share code, notes, and snippets.

@theasp
Last active January 2, 2022 02:32
Show Gist options
  • Save theasp/3a0a86639adac4bb915cd0684ff5934b to your computer and use it in GitHub Desktop.
Save theasp/3a0a86639adac4bb915cd0684ff5934b to your computer and use it in GitHub Desktop.
LDIF to YAML with some basic Base64 handling
#!/bin/bash
set -o pipefail
ldif_attr_re='^([^ :]+)(::?) (.+)$'
ldif_continue_re='^ (.+)$'
printable_re="^[[:print:]]+$"
yaml_attr_fmt='%s %s: "%s"\n'
declare -A RECORD
declare -A TYPE
function parse_ldif {
while IFS='' read line; do
# Skip LDIF comments
test "${line:0:1}" == "#" && continue;
if [[ -z $line ]]; then
first=true
for i in ${!RECORD[@]}; do
data=${RECORD[$i]}
type=${TYPE[$i]}
if [[ $type = '::' ]]; then
data=$(base64 -d <<<"$data" || true)
fi
if [[ -n $data ]]; then
if ! [[ $data =~ $printable_re ]]; then
data=$(base64 -w0 <<<"$data")
fi
data=${data//\"/\\\"}
data=${data//\\/\\\\}
indent=' '
if [[ $first = true ]]; then
indent='-'
first=false
fi
printf "$yaml_attr_fmt" "$indent" "$i" "$data"
fi
done
RECORD=()
TYPE=()
else
if [[ $line =~ $ldif_attr_re ]]; then
attr=${BASH_REMATCH[1]}
RECORD[$attr]=${BASH_REMATCH[3]}
TYPE[$attr]=${BASH_REMATCH[2]}
elif [[ $line =~ $ldif_continue_re ]]; then
RECORD[$attr]="${RECORD[$attr]}${BASH_REMATCH[1]}"
fi
fi
done
}
parse_ldif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment