Bash Script to Count Characters in a File
Use the command
wc -m filename in Bash to count the number of characters in a file, or use a script with char_count=$(wc -m < filename) to store the count.Examples
Inputfile.txt content: Hello
Output6
Inputfile.txt content: Hello World!
Output12
Inputfile.txt content: (empty file)
Output0
How to Think About It
To count characters in a file, think of reading the file's content and measuring how many characters it contains, including spaces and newlines. Bash provides a simple tool
wc -m that counts characters directly, so the script just needs to run this command and capture its output.Algorithm
1
Get the filename as input.2
Use the command to count characters in the file.3
Store or print the character count.Code
bash
#!/bin/bash filename="$1" if [[ ! -f "$filename" ]]; then echo "File not found!" exit 1 fi char_count=$(wc -m < "$filename") echo "Number of characters in '$filename': $char_count"
Output
Number of characters in 'file.txt': 12
Dry Run
Let's trace counting characters in a file containing 'Hello World!'
1
Check file existence
filename='file.txt' exists
2
Count characters
wc -m < file.txt returns '12'
3
Print result
Output: Number of characters in 'file.txt': 12
| Step | Action | Value |
|---|---|---|
| 1 | Check file | file.txt exists |
| 2 | Count characters | 12 |
| 3 | Print output | Number of characters in 'file.txt': 12 |
Why This Works
Step 1: Use wc -m to count characters
The wc -m command counts all characters in the file, including spaces and newlines.
Step 2: Redirect file content to wc
Using < filename sends the file content to wc without printing the filename.
Step 3: Store and print the count
The script saves the count in a variable and prints it with a clear message.
Alternative Approaches
Using awk
bash
awk '{ total += length($0) + 1 } END { print total }' filenameCounts characters including newline per line; may differ if file does not end with newline.
Using Perl
bash
perl -lne 'END { print $. ? $. + length($_) : 0 }' filenameMore complex but flexible for character counting with custom rules.
Complexity: O(n) time, O(1) space
Time Complexity
The command reads each character once, so time grows linearly with file size.
Space Complexity
No extra memory is needed beyond a few variables; counting is done on the fly.
Which Approach is Fastest?
wc -m is optimized and fastest; alternatives like awk or perl are slower but offer flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| wc -m | O(n) | O(1) | Simple, fast character count |
| awk | O(n) | O(1) | Custom line-based counting |
| perl | O(n) | O(1) | Flexible, complex counting |
Use
wc -m for a quick and reliable character count in Bash.Forgetting to redirect file content with
< filename causes wc to print filename along with count.