johnslattery
1/1/2017 - 7:12 PM

I used this to determine whether an 837 file was institutional or professional. It’s interesting in that it demonstrates a way to use read t

I used this to determine whether an 837 file was institutional or professional. It’s interesting in that it demonstrates a way to use read to break by anything and collect anything after the last delimiter, relying on the way read behaves expecting unix files to have a final carriage return at the end of the last line. If there is data after the carriage return it can be found in REPLY after read exits a while loop.

do_clm_file () {
  local file="$1"
  local buf=
  local seg_delim=
  local elem_delim=
  local sub_elem_delim=
  local -a segs=()
  local -a elems=()
  local -a sub_elems=()

  read -rN 4096 buf < "$file"
  
  seg_delim="${buf:105:1}"
  elem_delim="${buf:3:1}"
  sub_elem_delim="${buf:104:1}"

  while IFS= read -r -d "$seg_delim"; do
    segs+=( "$REPLY" )
  done <<< "$buf"
  [[ -n $REPLY ]] && segs+=( "${REPLY%$'\n'}" )

  while IFS= read -r -d "$elem_delim"; do
    elems+=( "$REPLY" )
  done <<< "${segs[1]}"
  [[ -n $REPLY ]] && elems+=( "${REPLY%$'\n'}" )
  
  printf "%s|%s\n" "$(get_file_name "$file")" "${elems[8]}"
}