dylanaraps / pure-bash-bible

📖 A collection of pure bash alternatives to external processes.
MIT License
36.54k stars 3.28k forks source link

Alternative to dos2unix #117

Open duskeer opened 3 years ago

duskeer commented 3 years ago
dos2unix() {
# Usage: dos2unix [FILE]
if (($#)); then
  dos2unix < "${1}"; return 0
fi
local now on none
while read -rN1 now; do
  case "${now}" in
    $'\r')
      on=1
      none=0
    ;;
    $'\n')
      printf -- '\n'
      none=0
    ;;
    *)
      printf -- '%s' "${now}"
    ;;
  esac
done
case "${on:-"0"}${none:-"1"}"  in
  10|01)
    printf -- '\n'
  ;;
esac
}
unix2dos() {
# Usage: unix2dos [FILE]
if (($#)); then
  unix2dos < "${1}"; return 0
fi
local now old
while read -rN1 now; do
  case "${now}" in
    $'\n'|$'\r')
      :
    ;;
    *)
      case "${old:-""}" in
        $'\n')
          printf -- '\r\n%s' "${now}"
        ;;
        *)
          printf -- '%s' "${now}"
        ;;
      esac
    ;;
  esac
  old="${now}"
done
}