Created
October 16, 2024 18:24
-
-
Save adde88/aa3e3a9a8752a088eddf22c195e62cc5 to your computer and use it in GitHub Desktop.
BASH: dos2unix & unix2dos (Will work on OpenWRT devices as well)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# | |
# This script will do the same as dos2unix and unix2dos, which are usable on Linux and Window. | |
# I made this so that i would be able to do the same on embedded devices like OpenWRT. | |
# | |
# Author: Andreas Nilsen <[email protected]> - @adde88 - http://www.github.com/adde88 | |
# Date: 16. October 2024 | |
# | |
# | |
function show_usage() { | |
echo "Usage: $0 [dos2unix|unix2dos] <filename(s)>" | |
echo "You can use wildcards for filename(s), e.g., *.txt" | |
echo | |
echo "Examples:" | |
echo " $0 dos2unix file.txt" | |
echo " $0 dos2unix *.cpp" | |
echo " $0 dos2unix *" | |
echo " $0 dos2unix file1.txt file2.txt file3.txt" | |
echo -e " Both dos2unix, and unix2dos can be used with the same arguments as demonstrated above.\n" | |
} | |
function dos2unix() { | |
local file="$1" | |
if [ ! -f "$file" ]; then | |
echo "File not found: $file" | |
return 1 | |
fi | |
sed -i 's/\r$//' "$file" | |
echo "Converted $file from DOS to UNIX format" | |
} | |
function unix2dos() { | |
local file="$1" | |
if [ ! -f "$file" ]; then | |
echo "File not found: $file" | |
return 1 | |
fi | |
sed -i 's/$/\r/' "$file" | |
echo "Converted $file from UNIX to DOS format" | |
} | |
# Check if no arguments or only one argument is provided | |
if [ $# -lt 2 ]; then | |
echo "Error: Insufficient arguments provided." | |
echo | |
show_usage | |
exit 1 | |
fi | |
conversion_type="$1" | |
shift | |
case "$conversion_type" in | |
dos2unix|unix2dos) | |
files_processed=0 | |
for file in "$@"; do | |
if [ -f "$file" ]; then | |
$conversion_type "$file" | |
((files_processed++)) | |
else | |
echo "Skipping $file: Not a regular file" | |
fi | |
done | |
if [ $files_processed -eq 0 ]; then | |
echo "Error: No valid files were processed." | |
echo | |
show_usage | |
exit 1 | |
fi | |
;; | |
*) | |
echo "Error: Invalid conversion type. Use 'dos2unix' or 'unix2dos'." | |
echo | |
show_usage | |
exit 1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I chose to use the shell for the work, as python seems to be quite slow on these devices compared to bash, or binaries compiled for the system, like C, C++