Skip to content

Commit dbae325

Browse files
authored
Merge pull request sumanth-0#796 from akashadsare/add-terminal-file-search
Add Terminal File Search - Issue sumanth-0#788
2 parents 233186c + 648b4c0 commit dbae325

File tree

2 files changed

+167
-0
lines changed

2 files changed

+167
-0
lines changed

Terminal_File_Search/README.md

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Terminal File Search
2+
3+
A minimal Python script to search for files in directories by name patterns or extensions, displaying results with full paths.
4+
5+
## Features
6+
7+
- **Name Search**: Find files using wildcards (`*.py`, `test*`, `file.txt`)
8+
- **Extension Search**: Search by file extension (`.py`, `.md`, `.txt`)
9+
- **Recursive Search**: Searches through all subdirectories
10+
- **Path Display**: Shows full paths for all matches
11+
- **Interactive Mode**: Prompts for directory and pattern
12+
- **Command Line**: Direct execution with arguments
13+
14+
## Usage
15+
16+
### Command Line
17+
```bash
18+
python file_search.py [directory] [pattern] [ext]
19+
```
20+
21+
### Interactive Mode
22+
```bash
23+
python file_search.py
24+
```
25+
26+
## Examples
27+
28+
### Search by Name Pattern
29+
```bash
30+
python file_search.py . "*.py"
31+
python file_search.py /home/user "test*"
32+
python file_search.py . "README.md"
33+
```
34+
35+
### Search by Extension
36+
```bash
37+
python file_search.py . ".py"
38+
python file_search.py /docs ".md"
39+
python file_search.py . "txt" ext
40+
```
41+
42+
### Interactive Example
43+
```
44+
Terminal File Search
45+
=========================
46+
Enter directory to search (or . for current): .
47+
Enter search pattern (e.g., *.py, test*, file.txt): *.py
48+
49+
Searching in: /current/directory
50+
Pattern: *.py (name)
51+
52+
Found 5 file(s) matching '*.py':
53+
--------------------------------------------------
54+
1. ./script.py
55+
2. ./utils/helper.py
56+
3. ./tests/test_main.py
57+
```
58+
59+
## Search Patterns
60+
61+
| Pattern | Description | Example |
62+
|---------|-------------|---------|
63+
| `*.py` | All Python files | `main.py`, `utils.py` |
64+
| `test*` | Files starting with "test" | `test_main.py`, `testing.txt` |
65+
| `README.md` | Exact filename | `README.md` |
66+
| `.py` | Extension search | All `.py` files |
67+
| `.md` | Extension search | All `.md` files |
68+
69+
## Requirements
70+
71+
- Python 3.6+
72+
- No external dependencies
73+
74+
## Error Handling
75+
76+
- Permission denied directories are skipped
77+
- Invalid directories show error message
78+
- Empty results display appropriate message
79+
80+
## Author
81+
82+
Created for issue #788 - 100 Lines of Python Code Project
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import sys
4+
import fnmatch
5+
6+
7+
def search_files(directory, pattern, search_type='name'):
8+
"""Search for files by name or extension."""
9+
matches = []
10+
11+
try:
12+
for root, dirs, files in os.walk(directory):
13+
for file in files:
14+
if search_type == 'extension':
15+
if file.lower().endswith(pattern.lower()):
16+
matches.append(os.path.join(root, file))
17+
else: # name search
18+
if fnmatch.fnmatch(file.lower(), pattern.lower()):
19+
matches.append(os.path.join(root, file))
20+
except PermissionError:
21+
print(f"Permission denied: {directory}")
22+
except Exception as e:
23+
print(f"Error searching: {e}")
24+
25+
return matches
26+
27+
28+
def display_results(matches, pattern):
29+
"""Display search results."""
30+
if not matches:
31+
print(f"No files found matching '{pattern}'")
32+
return
33+
34+
print(f"Found {len(matches)} file(s) matching '{pattern}':")
35+
print("-" * 50)
36+
37+
for i, match in enumerate(matches, 1):
38+
print(f"{i:3d}. {match}")
39+
40+
41+
def main():
42+
"""Main function."""
43+
print("Terminal File Search")
44+
print("=" * 25)
45+
46+
# Get directory
47+
if len(sys.argv) > 1:
48+
directory = sys.argv[1]
49+
else:
50+
directory = input("Enter directory to search (or . for current): ").strip()
51+
if not directory:
52+
directory = "."
53+
54+
if not os.path.exists(directory):
55+
print(f"Directory not found: {directory}")
56+
return
57+
58+
# Get search pattern
59+
if len(sys.argv) > 2:
60+
pattern = sys.argv[2]
61+
else:
62+
pattern = input("Enter search pattern (e.g., *.py, test*, file.txt): ").strip()
63+
if not pattern:
64+
print("No search pattern provided")
65+
return
66+
67+
# Determine search type
68+
if pattern.startswith('.') or (len(sys.argv) > 3 and sys.argv[3] == 'ext'):
69+
search_type = 'extension'
70+
if not pattern.startswith('.'):
71+
pattern = '.' + pattern
72+
else:
73+
search_type = 'name'
74+
75+
print(f"\nSearching in: {os.path.abspath(directory)}")
76+
print(f"Pattern: {pattern} ({search_type})")
77+
print()
78+
79+
# Search and display
80+
matches = search_files(directory, pattern, search_type)
81+
display_results(matches, pattern)
82+
83+
84+
if __name__ == "__main__":
85+
main()

0 commit comments

Comments
 (0)