Bash Script to Convert Uppercase to Lowercase File
tr '[:upper:]' '[:lower:]' < inputfile > outputfile to convert all uppercase letters in a file to lowercase.Examples
How to Think About It
Algorithm
Code
#!/bin/bash input_file="$1" output_file="$2" if [[ ! -f "$input_file" ]]; then echo "Input file does not exist." exit 1 fi tr '[:upper:]' '[:lower:]' < "$input_file" > "$output_file" echo "Converted $input_file to lowercase and saved as $output_file."
Dry Run
Let's trace converting 'HELLO WORLD' from input file SAMPLE.TXT to output file output.txt.
Check if input file exists
Input file SAMPLE.TXT exists.
Read input file content
Content read: 'HELLO WORLD'
Convert uppercase to lowercase
Converted content: 'hello world'
Write to output file
Output file output.txt now contains 'hello world'
Print confirmation
Printed message: Converted SAMPLE.TXT to lowercase and saved as output.txt.
| Step | Action | Value |
|---|---|---|
| 1 | Input file check | SAMPLE.TXT exists |
| 2 | Read content | HELLO WORLD |
| 3 | Convert content | hello world |
| 4 | Write output | output.txt with 'hello world' |
| 5 | Print message | Converted SAMPLE.TXT to lowercase and saved as output.txt. |
Why This Works
Step 1: Reading the file
The script reads the input file content using input redirection with <.
Step 2: Translating characters
The tr command replaces all uppercase letters [:upper:] with lowercase letters [:lower:].
Step 3: Saving output
The converted text is saved to the output file using output redirection with >.
Alternative Approaches
awk '{print tolower($0)}' inputfile > outputfilesed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' inputfile > outputfileComplexity: O(n) time, O(n) space
Time Complexity
The script processes each character once, so time grows linearly with file size.
Space Complexity
The output file requires space proportional to the input file size; the script uses minimal extra memory.
Which Approach is Fastest?
The tr command is generally fastest and simplest for this task compared to awk or sed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| tr command | O(n) | O(n) | Simple and fast character translation |
| awk tolower | O(n) | O(n) | More readable, supports complex processing |
| sed transliteration | O(n) | O(n) | Works well but less intuitive |