Skip to content

Commit 0b55331

Browse files
authored
Merge pull request sumanth-0#813 from aniruddhaadak9/issue-788-terminal-file-search
Add Terminal File Search Script - Resolves sumanth-0#788
2 parents 972e1bc + 0546452 commit 0b55331

File tree

2 files changed

+240
-0
lines changed

2 files changed

+240
-0
lines changed
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# Terminal File Search
2+
3+
A powerful command-line tool for searching files with various filters and options.
4+
5+
## Description
6+
7+
This Python script provides a comprehensive terminal-based file search utility that allows you to search for files based on multiple criteria including name patterns, file extensions, file types, and size ranges. It supports both recursive and non-recursive searches with detailed or simple output formats.
8+
9+
## Features
10+
11+
- **Name Pattern Search**: Search files using wildcard patterns (e.g., `*.txt`, `test_*`)
12+
- **Extension Filter**: Filter files by specific extensions
13+
- **Type Filter**: Search specifically for files or directories
14+
- **Size Range**: Filter by minimum and maximum file sizes
15+
- **Recursive Search**: Search through all subdirectories
16+
- **Verbose Output**: Display detailed information including file size and modification time
17+
- **Result Limiting**: Limit the number of search results
18+
- **Human-Readable Formats**: File sizes displayed in KB, MB, GB, etc.
19+
20+
## Requirements
21+
22+
- Python 3.6 or higher
23+
- No external dependencies (uses only standard library)
24+
25+
## Installation
26+
27+
1. Clone this repository or download the script
28+
2. Make the script executable (on Unix-like systems):
29+
```bash
30+
chmod +x terminal_file_search.py
31+
```
32+
33+
## Usage
34+
35+
### Basic Syntax
36+
```bash
37+
python terminal_file_search.py [directory] [options]
38+
```
39+
40+
### Options
41+
42+
- `-n, --name PATTERN`: File name pattern (supports wildcards like `*` and `?`)
43+
- `-e, --ext EXTENSION`: File extension without dot (e.g., `py`, `txt`)
44+
- `-t, --type TYPE`: Type filter - `f` for files, `d` for directories
45+
- `--min-size SIZE`: Minimum file size in KB
46+
- `--max-size SIZE`: Maximum file size in KB
47+
- `-r, --recursive`: Search recursively through subdirectories
48+
- `-v, --verbose`: Show detailed output with file size and modification time
49+
- `-l, --limit NUMBER`: Limit the number of results
50+
51+
### Examples
52+
53+
#### Search for all Python files in current directory
54+
```bash
55+
python terminal_file_search.py -e py
56+
```
57+
58+
#### Search recursively for files starting with "test"
59+
```bash
60+
python terminal_file_search.py -n "test*" -r
61+
```
62+
63+
#### Find all files larger than 100KB
64+
```bash
65+
python terminal_file_search.py --min-size 100 -r
66+
```
67+
68+
#### Search for directories only
69+
```bash
70+
python terminal_file_search.py -t d -r
71+
```
72+
73+
#### Verbose search for text files with size constraints
74+
```bash
75+
python terminal_file_search.py -e txt --min-size 10 --max-size 1000 -r -v
76+
```
77+
78+
#### Search in specific directory with result limit
79+
```bash
80+
python terminal_file_search.py /path/to/directory -n "*.log" -r -l 10
81+
```
82+
83+
#### Combine multiple filters
84+
```bash
85+
python terminal_file_search.py . -e py -n "*test*" --min-size 5 -r -v
86+
```
87+
88+
## Output Format
89+
90+
### Standard Output
91+
```
92+
/path/to/file1.py
93+
/path/to/file2.py
94+
```
95+
96+
### Verbose Output
97+
```
98+
/path/to/file1.py | Size: 15.43 KB | Modified: 2025-10-12 20:30:15
99+
/path/to/file2.py | Size: 8.21 KB | Modified: 2025-10-11 14:22:08
100+
```
101+
102+
## Error Handling
103+
104+
- Gracefully handles permission errors
105+
- Skips files/directories that cannot be accessed
106+
- Provides informative error messages
107+
108+
## Contributing
109+
110+
Contributions are welcome! Please feel free to submit a Pull Request.
111+
112+
## License
113+
114+
This project is open source and available under the MIT License.
115+
116+
## Issue Reference
117+
118+
This implementation resolves issue #788 - Terminal File Search
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Terminal File Search
4+
A powerful command-line tool for searching files with various filters.
5+
"""
6+
7+
import os
8+
import sys
9+
import argparse
10+
from pathlib import Path
11+
import fnmatch
12+
from datetime import datetime
13+
14+
15+
def format_size(size):
16+
"""Format file size in human-readable format."""
17+
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
18+
if size < 1024.0:
19+
return f"{size:.2f} {unit}"
20+
size /= 1024.0
21+
return f"{size:.2f} PB"
22+
23+
24+
def format_time(timestamp):
25+
"""Format timestamp to readable date."""
26+
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
27+
28+
29+
def matches_criteria(file_path, args):
30+
"""Check if file matches all search criteria."""
31+
try:
32+
stat = file_path.stat()
33+
34+
# Check name pattern
35+
if args.name and not fnmatch.fnmatch(file_path.name, args.name):
36+
return False
37+
38+
# Check extension
39+
if args.ext and not file_path.suffix.lower() == f".{args.ext.lower()}":
40+
return False
41+
42+
# Check minimum size
43+
if args.min_size and stat.st_size < args.min_size * 1024:
44+
return False
45+
46+
# Check maximum size
47+
if args.max_size and stat.st_size > args.max_size * 1024:
48+
return False
49+
50+
# Check file type
51+
if args.type:
52+
if args.type == 'f' and not file_path.is_file():
53+
return False
54+
if args.type == 'd' and not file_path.is_dir():
55+
return False
56+
57+
return True
58+
except (OSError, PermissionError):
59+
return False
60+
61+
62+
def search_files(directory, args):
63+
"""Search files in directory based on criteria."""
64+
results = []
65+
try:
66+
path = Path(directory).resolve()
67+
68+
for item in path.rglob('*') if args.recursive else path.glob('*'):
69+
if matches_criteria(item, args):
70+
results.append(item)
71+
72+
if args.limit and len(results) >= args.limit:
73+
break
74+
except PermissionError:
75+
print(f"Permission denied: {directory}", file=sys.stderr)
76+
77+
return results
78+
79+
80+
def display_results(results, args):
81+
"""Display search results."""
82+
if not results:
83+
print("No files found matching the criteria.")
84+
return
85+
86+
print(f"\nFound {len(results)} file(s):\n")
87+
88+
for file_path in sorted(results):
89+
if args.verbose:
90+
try:
91+
stat = file_path.stat()
92+
size = format_size(stat.st_size)
93+
mtime = format_time(stat.st_mtime)
94+
print(f"{file_path} | Size: {size} | Modified: {mtime}")
95+
except OSError:
96+
print(file_path)
97+
else:
98+
print(file_path)
99+
100+
101+
def main():
102+
parser = argparse.ArgumentParser(
103+
description="Search files in terminal with various filters"
104+
)
105+
parser.add_argument('directory', nargs='?', default='.', help='Directory to search (default: current)')
106+
parser.add_argument('-n', '--name', help='File name pattern (supports wildcards)')
107+
parser.add_argument('-e', '--ext', help='File extension (without dot)')
108+
parser.add_argument('-t', '--type', choices=['f', 'd'], help='Type: f=file, d=directory')
109+
parser.add_argument('--min-size', type=int, help='Minimum file size in KB')
110+
parser.add_argument('--max-size', type=int, help='Maximum file size in KB')
111+
parser.add_argument('-r', '--recursive', action='store_true', help='Search recursively')
112+
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output with details')
113+
parser.add_argument('-l', '--limit', type=int, help='Limit number of results')
114+
115+
args = parser.parse_args()
116+
117+
results = search_files(args.directory, args)
118+
display_results(results, args)
119+
120+
121+
if __name__ == "__main__":
122+
main()

0 commit comments

Comments
 (0)