Bash Script to Convert DOS to UNIX Line Endings
sed -i 's/\r$//' filename to convert DOS line endings to UNIX line endings by removing carriage return characters.Examples
How to Think About It
\r that appears before the newline \n in DOS files. The script should scan each line and delete the trailing \r if present, leaving only the UNIX newline \n.Algorithm
Code
#!/bin/bash if [ $# -ne 1 ]; then echo "Usage: $0 filename" exit 1 fi filename="$1" # Remove carriage return characters at end of lines sed -i 's/\r$//' "$filename" echo "Converted DOS to UNIX line endings in $filename"
Dry Run
Let's trace converting a file with DOS line endings 'Line1\r\nLine2\r\n' through the script.
Input file content
Line1\r\nLine2\r\n
sed command processes each line
For line 'Line1\r', sed removes '\r' at end, resulting in 'Line1'
Second line processed
For line 'Line2\r', sed removes '\r' at end, resulting in 'Line2'
File saved with UNIX line endings
Final content: 'Line1\nLine2\n'
| Step | Line Before | Line After |
|---|---|---|
| 1 | Line1\r | Line1 |
| 2 | Line2\r | Line2 |
Why This Works
Step 1: Why remove \r characters?
DOS line endings use \r\n (carriage return + newline), but UNIX uses only \n. Removing \r converts the file to UNIX style.
Step 2: How sed works here
The sed command uses the pattern s/\r$// to find a carriage return at the end of each line and delete it.
Step 3: In-place editing
The -i option edits the file directly, so the changes replace the original content.
Alternative Approaches
dos2unix filename
tr -d '\r' < filename > newfileawk '{ sub(/\r$/, ""); print }' filename > newfileComplexity: O(n) time, O(1) space
Time Complexity
The script processes each line once, so time grows linearly with file size.
Space Complexity
The operation is done in-place with sed -i, so extra space is minimal.
Which Approach is Fastest?
Using sed -i or dos2unix is fastest for in-place conversion; tr and awk require extra file writes.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sed -i | O(n) | O(1) | Quick in-place edits |
| dos2unix | O(n) | O(1) | Dedicated tool, easy use |
| tr | O(n) | O(n) | Simple removal, new file output |
| awk | O(n) | O(n) | Flexible processing, new file output |
-i option with sed causes output to print on screen instead of modifying the file.