Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # dos to unix converter
- # changes dos line endings to unix line endings
- # control eol chars
- CR="\15"
- LF="\32"
- CRLF="\15\32"
- DEBUG_MODE=
- function check_stdin
- {
- [[ -t 0 ]] && \
- echo 'STDIN is attached to TTY'
- [[ -p /dev/stdin ]] && \
- echo 'STDIN is attached to a pipe'
- [[ ! -t 0 && ! -p /dev/stdin ]] && \
- echo 'STDIN is attached to a redirection'
- }
- function check_stdout
- {
- [[ -t 1 ]] && \
- echo 'STDOUT is attached to TTY'
- [[ -p /dev/stdout ]] && \
- echo 'STDOUT is attached to a pipe'
- [[ ! -t 1 && ! -p /dev/stdout ]] && \
- echo 'STDOUT is attached to a redirection'
- }
- [[ $DEBUG_MODE ]] && echo "DEBUG MODE" && check_stdin && check_stdin && exit
- DONE=
- TR=$(which tr)
- if [[ ! "${TR}" ]]
- then
- echo -e "ERROR -- can;t find tr binary in executable path."
- usage
- exit -1
- fi
- if [[ ! $TEMPDIR ]]
- then
- TEMPDIR="/tmp"
- fi
- if [ -t 0 ]
- then
- # echo "terminal input"
- TERMIN=1
- fi
- if [ -t 1 ]
- then
- # echo "terminal output"
- TERMOUT=1
- fi
- # don't automatically overwrite files
- check_overwrite()
- {
- read -p "overwrite existing file ${1} ? [Y]" do_overwrite
- do_overwrite=${do_overwrite,,} # tolower
- if [[ $do_overwrite =~ ^(yes|y)$ ]] ; then
- return 1
- else
- return 0
- fi
- }
- # help
- usage()
- {
- cat <<EOF
- Usage: d2u <file>
- if no outfile is specified,
- <textfile> is overwritten.
- d2u <inputfile> <outputfile>
- [file output] | d2u | [file input]
- use d2u as a text filter
- EOF
- }
- if [ "X${1}" == "Xhelp" ] ; then
- usage
- exit 0
- fi
- if [ $# -gt 2 ] ; then
- usage
- exit -1
- fi
- if [ ! -f "${1}" ]
- then
- # filter just tr <stdin> tr <stdout>
- if [[ ! $DONE ]] && [[ $TERMIN ]] && [[ $TERMOUT ]]
- then
- ${TR} -d '\15\32'
- DONE=1
- fi
- # translate a pipe
- if [[ ! $DONE ]] && [[ $TERMOUT ]] && [[ ! $TERMIN ]]
- then
- ${TR} -d '\15\32'
- DONE=1
- fi
- fi
- # translate a file
- if [[ ! $DONE ]] && [[ $TERMIN ]] && [ -f "${1}" ]
- then
- newfile="${TEMPDIR}/tr.temp"
- ${TR} -d '\15\32' < "${1}" > "${newfile}"
- if [ -e "${newfile}" ]; then
- mv "${1}" "${1}.tr.old"
- mv "${newfile}" "${1}"
- fi
- DONE=1
- fi
- # translate output from file
- if [[ ! $DONE ]] && [ -f "${1}" ] && [[ $TERMOUT ]]
- then
- newfile=
- ${TR} -d '\15\32' < "${1}"
- DONE=1
- fi
- # make separate translated file from a file
- if [[ ! $DONE ]] && [ -f "${1}" ] && [ -f "${2}" ]
- then
- newfile="${TEMPDIR}/tr.temp"
- ${TR} -d '\15\32' < "${1}" > "${newfile}"
- if [ -e "${newfile}" ]; then
- check_overwrite "${2}"
- result=$? #result of last function
- if [[ $result -eq 1 ]] ; then
- mv "${newfile}" "${2}"
- else
- echo "creating file ${2}.d2u"
- mv "${newfile}" "${2}.d2u"
- fi
- fi
- DONE=1
- fi
- #END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement