readlines 1.5 → 1.6

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1b5fb4edb74d65584c625105a679e4a9d7523bdd5437ef733932c46b888723b5
4
- data.tar.gz: 9608ee45bc3e1f89f684f37edd1c69ef9d901918d09a0b5bc404aca13aafcfc4
3
+ metadata.gz: 573d78464068c0e851233a9618a588a95eb90faac37369a57bf60b9f304157be
4
+ data.tar.gz: d717ea49cbb087b333480feb9d842d43a72e2f7da4b82fd4987f27ab83291959
5
5
  SHA512:
6
- metadata.gz: 4c5df729b5497190c5aa8ad6fb880d96fdd50e6f17cd94f3cee9380cf7b420808f4855603387880a854a76ae0420dde7bddf1d26a682383a4d1b578b810dfe19
7
- data.tar.gz: 1ec0f06aa5b3851f15bbf65b888888e38672cf3ab3dde593564f0a55f589c99e687ad25194f8c8275a855c98132ef4b07e91aa1fbea73a37adebfb8836433258
6
+ metadata.gz: 49315052d03f5102941ff900893e045268522e7d661c6edb1e0d6426cb53bd3b4b8d2a902b9eb6afd5e807b38e32f7fa6cb46adbbe3c8607359c7d5809a841e5
7
+ data.tar.gz: 191227637e442aa45f2fdd4dc23e239be88ff354a0c24fddf7e3cf38e4d8f38b735f77b9277975186bade948c85952d8f28690d683209907937043b831134bab
data/README.md CHANGED
@@ -5,346 +5,274 @@ Readlines is a powerful and versatile Ruby library for file manipulation and pro
5
5
 
6
6
  ## Features
7
7
 
8
- - Read the entire file content or specific parts of it.
9
- - Search for specific values in the file and display matching line numbers.
10
- - Count the number of lines in the file based on a keyword or delimiter.
11
- - Replace specific patterns in the file with replacement text.
12
- - Remove empty lines from the file.
13
- - Sort the lines of the file alphabetically.
14
- - Split the file into a specified number of parts.
15
- - Merge multiple files into a single file.
16
- - Convert the encoding of the file from one encoding to another.
17
- - Replace special characters in the file with a replacement string.
18
- - Remove unwanted characters from the file.
19
- - Split the file by a specified size.
20
- - Convert the file to a specified format (txt, csv, json).
21
- - Search for multiple patterns in the file and count occurrences of each pattern.
22
- - Replace multiple patterns in the file in a single operation.
23
- - Split the file based on a specified delimiter.
24
- - Merge multiple files into a single file with a specified separator between each file's content.
25
- - Check if a specific pattern exists in the file.
26
- - Delete specific lines from the file with the option to remove resulting empty lines.
27
- - Reverse the order of the file contents.
28
- - Search for a pattern within a specified range of lines.
29
- - Count the number of characters in the file or in a specific line.
30
- - Count the number of words in the file or in a specific line.
31
- - Extract specific patterns from the file.
32
- - Convert the file contents into an array of lines.
33
- - Validate the file contents against a set of rules.
34
- - Remove duplicate lines from the file.
35
- - Get statistics about the file (number of lines, characters, words).
36
- - Search for logical patterns in the file using AND and OR operators.
37
- - Split the file based on a specified pattern.
38
- - Delete specific columns from a CSV file.
39
- - Replace a specific value in a CSV column.
40
- - Check for spelling errors in the file using a dictionary.
41
- - Encrypt the file contents using a key.
42
- - Decrypt the encrypted file contents using a key.
43
- - Get the file size in different units (bytes, kilobytes, megabytes, gigabytes).
8
+ - **File Reading**: Read the entire file content or specific parts.
9
+ - **Search Operations**: Search for values and display matching line numbers.
10
+ - **Line Counting**: Count lines based on keywords or delimiters.
11
+ - **Pattern Replacement**: Replace specific patterns or multiple patterns at once.
12
+ - **Delete Empty Lines**: Remove empty lines.
13
+ - **Alphabetical Sorting**: Sort lines alphabetically.
14
+ - **File Splitting**: Split files into parts or by size.
15
+ - **File Merging**: Merge multiple files with a separator.
16
+ - **Encoding Conversion**: Convert file encoding.
17
+ - **Character Replacement**: Replace special characters or unwanted characters.
18
+ - **Format Conversion**: Convert the file to txt, csv, or json.
19
+ - **Multiple Pattern Search**: Search and count multiple patterns.
20
+ - **Delimiter-Based Splitting**: Split files by delimiter or pattern.
21
+ - **Pattern Checking**: Check if patterns exist.
22
+ - **Delete Specific Lines**: Delete lines, specific columns in CSV, and duplicates.
23
+ - **Reverse Content**: Reverse the file’s content.
24
+ - **Range-Based Search**: Search within a specific line range.
25
+ - **Character and Word Counting**: Count characters or words.
26
+ - **Pattern Extraction**: Extract specific patterns.
27
+ - **Content Validation**: Validate against custom rules.
28
+ - **Logical Pattern Search**: AND/OR based pattern search.
29
+ - **Spelling Check**: Detect spelling errors with a dictionary.
30
+ - **Encryption/Decryption**: Encrypt and decrypt content.
31
+ - **File Size Calculation**: Display size in bytes, KB, MB, or GB.
32
+ - **Filter Operation**: Delete or replace lines based on matching criteria (`:start`, `:body`, or `:end`).
44
33
 
45
34
  ## Installation
46
35
 
47
- To use the Readlines library in your Ruby project, you can install it via RubyGems. Run the following command:
36
+ To use the Readlines library in your Ruby project, install it via RubyGems:
48
37
 
49
- ```
38
+ ```bash
50
39
  gem install readlines
51
40
  ```
52
41
 
53
- Alternatively, you can add the following line to your project's Gemfile:
42
+ Or add it to your Gemfile:
54
43
 
55
44
  ```ruby
56
45
  gem 'readlines'
57
46
  ```
58
47
 
59
- Then, run `bundle install` to install the library and its dependencies.
48
+ Run `bundle install` to install the library and its dependencies.
60
49
 
61
50
  ## Usage
62
51
 
63
- To start using the Readlines library, require it in your Ruby script:
52
+ Start by requiring `readlines` in your Ruby script:
64
53
 
65
54
  ```ruby
66
55
  require 'readlines'
67
56
  ```
68
57
 
69
- Create an instance of the `Read` class, providing the path to the file you want to work with:
58
+ Create an instance of the `Read` class with the filename (or full path):
70
59
 
71
60
  ```ruby
72
- file_path = '/path/to/your/file.txt'
73
- read = Read.new(file_path)
61
+ file_name = 'file.txt'
62
+ read = Read.new(file_name)
74
63
  ```
75
64
 
76
- Now you can use the various methods provided by the library to manipulate and process the file contents. Here are some examples:
77
- ```ruby
78
- # imagen you have file inside of it data like this and you want count all data of names how manually no you can use this method and that will count for you body 😁
79
- # ++++++++++++++++++++++++++++++++++++
80
- # name : 'john'
81
- # phone : '+1 332-332-3322'
82
- #++++++++++++++++++++++++++++++++++++
83
- read = Read.new(file_path, count: 'name', split: '++++++++++++++++++++++++++++++++++++')
84
- puts read.line_count
85
- ```
65
+ ### Examples
66
+
67
+ #### Basic Operations
86
68
  ```ruby
87
69
  # Read the entire file content
88
70
  content = read.read_lines
89
71
  puts content
90
72
  ```
73
+
74
+ #### Counting Operations
91
75
  ```ruby
92
- # Search for a specific value in the file and display matching line numbers
93
- value = 'example'
94
- result = read.search_about(value, show_lines: true)
95
- puts result
96
- ```
97
- ```ruby
98
- # Count the number of lines in the file based on a keyword or delimiter
99
- keyword = 'example'
100
- delimiter = '---'
101
- count = read.line_count(count: keyword, split: delimiter)
76
+ # Count lines containing a specific keyword
77
+ count = read.line_count(count: 'example')
102
78
  puts count
79
+
80
+ # Count characters in the file or a specific line
81
+ total_characters = read.character_count
82
+ puts total_characters
83
+ line_characters = read.character_count(line_specific: 3)
84
+ puts line_characters
85
+
86
+ # Count words in the file or a specific line
87
+ total_words = read.word_count
88
+ puts total_words
89
+ line_words = read.word_count(line_specific: 3)
90
+ puts line_words
103
91
  ```
92
+
93
+ #### Search Operations
104
94
  ```ruby
105
- # Replace specific patterns in the file with replacement text
106
- pattern = /example/
107
- replacement = 'new_example'
108
- updated_content = read.replace(pattern, replacement)
109
- puts updated_content
95
+ # Search for a specific value and show line numbers
96
+ result = read.search_about('example', show_lines: true)
97
+ puts result
98
+
99
+ # Search for multiple patterns and count occurrences
100
+ patterns = [/example/, /test/]
101
+ result = read.search_multiple_patterns(patterns)
102
+ puts result
103
+
104
+ # Check if a pattern exists
105
+ pattern_exists = read.pattern_exists?(/example/)
106
+ puts pattern_exists
107
+
108
+ # Search for a pattern within a range of lines
109
+ matched_lines = read.search_in_range(5, 10, /example/)
110
+ puts matched_lines
111
+
112
+ # Logical pattern search (AND/OR operators)
113
+ and_results = read.search_logical_patterns([/example/, /test/], 'AND')
114
+ puts and_results
115
+ or_results = read.search_logical_patterns([/example/, /test/], 'OR')
116
+ puts or_results
110
117
  ```
118
+
119
+ #### Replacement Operations
111
120
  ```ruby
112
- # Remove empty lines from the file
113
- updated_content = read.remove_empty_lines
121
+ # Replace specific patterns in the file
122
+ updated_content = read.replace(/example/, 'new_example')
114
123
  puts updated_content
115
- ```
116
- ```ruby
117
- # Sort the lines of the file alphabetically
118
- sorted_content = read.sort_alphabetically
119
- puts sorted_content
120
- ```
121
- ```ruby
122
- # Split the file into a specified number of parts
123
- num_parts = 3
124
- read.split_file(num_parts)
125
- ```
126
- ```ruby
127
- # Merge multiple files into a single file
128
- file_paths = ['/path/to/file1.txt', '/path/to/file2.txt']
129
- merged_file = read.merge_files(file_paths)
130
- puts merged_file
131
- ```
132
- ```ruby
133
- # Convert the encoding of the file from one encoding to another
134
- from_encoding = 'UTF-8'
135
- to_encoding = 'ISO-8859-1'
136
- read.convert_encoding(from_encoding, to_encoding)
137
- ```
138
- ```ruby
139
- # Replace special characters in the file with a replacement string
140
- replacement = '_'
141
- updated_content = read.replace_special_characters(replacement)
124
+
125
+ # Replace multiple patterns at once
126
+ pattern_replacement = {/example/ => 'new_example', /test/ => 'new_test'}
127
+ updated_content = read.replace_multiple_patterns(pattern_replacement)
142
128
  puts updated_content
143
- ```
144
- ```ruby
145
- # Remove unwanted characters from the file
146
- unwanted_chars = '!@#$%^&*()'
147
- updated_content = read.remove_unwanted_characters(unwanted_chars)
129
+
130
+ # Replace characters in a CSV column
131
+ updated_csv = read.replace_csv_value(2, 'old_value', 'new_value')
132
+ puts updated_csv
133
+
134
+ # Replace special characters with a specified replacement string
135
+ updated_content = read.replace_special_characters('_')
148
136
  puts updated_content
149
137
  ```
138
+
139
+ #### Deletion Operations
150
140
  ```ruby
151
- # Split the file by a specified size
152
- part_size = 1024 # 1 KB
153
- read.split_file_by_size(part_size)
154
- ```
155
- ```ruby
156
- # Convert the file to a specified format
157
- format = 'csv'
158
- converted_file = read.convert_to_format(format)
159
- puts converted_file
160
- ```
161
- ```ruby
162
- # Search for multiple patterns in the file and count occurrences of each pattern
163
- patterns = [/example/, /pattern/]
164
- result = read.search_multiple_patterns(patterns)
165
- puts result
166
- ```
167
- ```ruby
168
- # Replace multiple patterns in the file in a single operation
169
- pattern_replacement_hash = {/example/ => 'new_example', /pattern/ => 'new_pattern'}
170
- updated_content = read.replace_multiple_patterns(pattern_replacement_hash)
141
+ # Delete empty lines from the file
142
+ updated_content = read.delete_empty_lines
171
143
  puts updated_content
172
- ```
173
- ```ruby
174
- # Split the file based on a specified delimiter
175
- delimiter = '---'
176
- read.split_by_delimiter(delimiter)
177
- ```
178
- ```ruby
179
- # Merge multiple files into a single file with a specified separator between each file's content
180
- file_paths = ['/path/to/file1.txt', '/path/to/file2.txt']
181
- separator = '---'
182
- merged_file = read.merge_files(file_paths, separator: separator)
183
- puts merged_file
184
- ```
185
- ```ruby
186
- # Check if a specific pattern exists in the file
187
- pattern = /example/
188
- exists = read.pattern_exists?(pattern)
189
- puts exists
190
- ```
191
- ```ruby
192
- # Delete specific lines from the file with the option to remove resulting empty lines
193
- line_numbers = [2, 4, 6]
194
- updated_content = read.delete_lines(line_numbers, delete_space: true)
144
+
145
+ # Delete specific lines with the option to remove empty lines
146
+ updated_content = read.delete_lines([2, 4, 6], delete_space: true)
195
147
  puts updated_content
148
+
149
+ # Delete unwanted characters
150
+ updated_content = read.delete_unwanted_characters('!@#$%^')
151
+ puts updated_content
152
+
153
+ # Delete duplicate lines
154
+ unique_content = read.delete_duplicate_lines
155
+ puts unique_content
156
+
157
+ # Delete specific columns in a CSV file
158
+ updated_csv = read.delete_csv_columns([1, 3])
159
+ puts updated_csv
160
+
161
+ # Filter lines based on criteria
162
+ # Replace lines starting with "hello" with "hi"
163
+ read.filter("hello", :start, :replace, "hi")
164
+ read.filter("world", :body, :replace, "guys")
165
+ read.filter("123", :end, :replace, "456")
166
+
167
+ # Delete lines containing "unwanted_text" from start or end or anywhere using `:start` or `:end` or `:body`
168
+ read.filter("unwanted_text", :start, :delete)
169
+ read.filter("unwanted_text", :body, :delete)
170
+ read.filter("unwanted_text", :end, :delete)
196
171
  ```
172
+
173
+ #### File Splitting and Merging
197
174
  ```ruby
198
- # Reverse the order of the file contents
199
- reversed_content = read.reverse_content
200
- puts reversed_content
201
- ```
202
- ```ruby
203
- # Search for a pattern within a specified range of lines
204
- start_line = 5
205
- end_line = 10
206
- pattern = /example/
207
- matched_lines = read.search_in_range(start_line, end_line, pattern)
208
- puts matched_lines
209
- ```
210
- ```ruby
211
- # Count the number of characters in the file or in a specific line
212
- total_characters = read.character_count
213
- puts total_characters
175
+ # Split the file into 3 parts
176
+ read.split_file(3)
214
177
 
215
- line_number = 3
216
- line_characters = read.character_count(line_specific: line_number)
217
- puts line_characters
178
+ # Split by size (in bytes)
179
+ read.split_file_by_size(1024) # 1 KB
180
+
181
+ # Split by delimiter
182
+ read.split_by_delimiter('---')
183
+
184
+ # Split by a pattern
185
+ read.split_by_pattern(/Chapter \d+/)
186
+
187
+ # Merge multiple files
188
+ merged_file = read.merge_files(['/path/to/file1.txt', '/path/to/file2.txt'])
189
+ puts merged_file
190
+
191
+ # Merge files with a separator
192
+ merged_file_with_separator = read.merge_files(['/file1.txt', '/file2.txt'], separator: '---')
193
+ puts merged_file_with_separator
218
194
  ```
195
+
196
+ #### Encoding and Format Conversion
219
197
  ```ruby
220
- # Count the number of words in the file or in a specific line
221
- total_words = read.word_count
222
- puts total_words
198
+ # Convert encoding
199
+ read.convert_encoding('UTF-8', 'ISO-8859-1')
223
200
 
224
- line_number = 3
225
- line_words = read.word_count(line_specific: line_number)
226
- puts line_words
201
+ # Convert file format to CSV
202
+ converted_csv = read.convert_to_format('csv')
203
+ puts converted_csv
227
204
  ```
205
+
206
+ #### Extracting and Validating Content
228
207
  ```ruby
229
- # Extract specific patterns from the file
208
+ # Extract specific patterns (e.g., email addresses)
230
209
  patterns = [/email:\s*\S+/, /phone:\s*\S+/]
231
210
  extracted_data = read.extract_patterns(patterns)
232
211
  puts extracted_data
233
- ```
234
- ```ruby
235
- # Convert the file contents into an array of lines
236
- lines_array = read.convert_to_array
237
- puts lines_array
238
- ```
239
- ```ruby
240
- # Validate the file contents against a set of rules
212
+
213
+ # Validate content with a set of rules
241
214
  rules = [/^[A-Z]/, /\b\d{3}-\d{3}-\d{4}\b/]
242
215
  is_valid = read.validate_content(rules)
243
216
  puts is_valid
244
- ```
245
- ```ruby
246
- # Remove duplicate lines from the file
247
- unique_content = read.delete_duplicate_lines
248
- puts unique_content
249
- ```
250
- ```ruby
251
- # Get statistics about the file
252
- stats = read.file_statistics
253
- puts stats
254
- ```
255
- ```ruby
256
- # Search for logical patterns in the file using AND and OR operators
257
- patterns = [/example/, /pattern/]
258
- and_matched_lines = read.search_logical_patterns(patterns, 'AND')
259
- puts and_matched_lines
260
- ```
261
- ```ruby
262
- or_matched_lines = read.search_logical_patterns(patterns, 'OR')
263
- puts or_matched_lines
264
- ```
265
- ```ruby
266
- # Split the file based on a specified pattern
267
- pattern = /Chapter \d+:/
268
- read.split_by_pattern(pattern)
269
- ```
270
- ```ruby
271
- # Delete specific columns from a CSV file
272
- column_indices = [1, 3]
273
- updated_csv = read.delete_csv_columns(column_indices)
274
- puts updated_csv
275
- ```
276
- ```ruby
277
- # Replace a specific value in a CSV column
278
- column_index = 2
279
- old_value = 'old_value'
280
- new_value = 'new_value'
281
- updated_csv = read.replace_csv_value(column_index, old_value, new_value)
282
- puts updated_csv
283
- ```
284
- ```ruby
285
- # Check for spelling errors in the file using a dictionary
217
+
218
+ # Check for spelling errors using a dictionary
286
219
  dictionary = ['example', 'pattern', 'file']
287
220
  misspelled_words = read.check_spelling(dictionary)
288
221
  puts misspelled_words
289
222
  ```
223
+
224
+ #### File Size and Statistics
290
225
  ```ruby
291
- # Encrypt the file contents using a key
292
- key = 5
293
- encrypted_file = read.encrypt_content(key)
294
- puts encrypted_file
295
- ```
296
- ```ruby
297
- # Decrypt the encrypted file contents using a key
298
- encrypted_file_path = '/path/to/encrypted_file.txt'
299
- decrypted_file = read.decrypt_content(key, encrypted_file_path)
300
- puts decrypted_file
301
- ```
302
- ```ruby
303
- # Get the file size in different units
226
+ # Get file size in different units
304
227
  file_size_bytes = read.file_size
305
228
  puts file_size_bytes
306
-
307
229
  file_size_kb = read.file_size(unit: :kilobytes)
308
230
  puts file_size_kb
309
-
310
231
  file_size_mb = read.file_size(unit: :megabytes)
311
232
  puts file_size_mb
312
-
313
233
  file_size_gb = read.file_size(unit: :gigabytes)
314
234
  puts file_size_gb
235
+
236
+ # Get statistics about the file
237
+ file_stats = read.file_statistics
238
+ puts file_stats
239
+ ```
240
+
241
+ #### Encryption and Decryption
242
+ ```ruby
243
+ # Encrypt content using a key
244
+ encrypted_content = read.encrypt_content(5)
245
+ puts encrypted_content
246
+
247
+ # Decrypt the content using the same key
248
+ decrypted_content = read.decrypt_content(5, '/path/to/encrypted_file.txt')
249
+ puts decrypted_content
250
+ ```
251
+
252
+ #### Reverse and Additional Operations
253
+ ```ruby
254
+ # Reverse the order of file contents
255
+ reversed_content = read.reverse_content
256
+ puts reversed_content
315
257
  ```
316
258
 
317
259
  ## Error Handling
318
260
 
319
- The Readlines library provides custom error classes to handle specific exceptions:
261
+ The Readlines library provides custom error classes for handling specific exceptions:
320
262
 
321
- - `Readlines::Error`: General error class for all exceptions in the library.
322
- - `Readlines::NotFoundError`: Raised when a file is not found.
323
- - `Readlines::MissingFilePathError`: Raised when a file path is missing or empty.
324
- - `Readlines::InvalidUnitError`: Raised when an invalid unit is provided for file size conversion.
263
+ - **Readlines::Error**: General error class for all exceptions.
264
+ - **Readlines::NotFoundError**: Raised when the file is not found.
265
+ - **Readlines::MissingFilePathError**: Raised when a file path is missing or empty.
266
+ - **Readlines::InvalidUnitError**: Raised for invalid file size units.
325
267
 
326
268
  These error classes help in handling and debugging exceptions that may occur while using the library.
327
269
 
328
270
  ## Contributing
329
271
 
330
- Contributions to the Readlines library are welcome! If you find any bugs, have suggestions for improvements, or want to add new features, please open an issue or submit a pull request on the [GitHub repository](https://github.com/abo5/readlines).
272
+ Contributions are welcome! If you find bugs, have suggestions, or want to add features, please open an issue or submit a pull request on the [GitHub repository](https://github.com/abo5/readlines).
331
273
 
332
274
  When contributing, please ensure that your code follows the existing coding style and includes appropriate tests.
333
275
 
334
276
  ## License
335
277
 
336
- The Readlines library is open-source and released under the [MIT License](https://opensource.org/licenses/MIT). You are free to use, modify, and distribute the library in accordance with the terms of the license.
337
-
338
- ## Contact
339
-
340
- If you have any questions, suggestions, or feedback regarding the Readlines library, please feel free to contact the maintainer:
341
-
342
- - Name: Maven
343
- - GitHub: [Maven's GitHub](https://github.com/abo5)
344
-
345
- We appreciate your interest in the Readlines library and look forward to your contributions and feedback!
346
-
347
-
348
-
349
- # readlines
350
- # readlines
278
+ The Readlines library is open-source and released under the [MIT License](https://opensource.org/licenses/MIT).
@@ -13,6 +13,7 @@ require_relative 'readlines/replace'
13
13
  require_relative 'readlines/search'
14
14
  require_relative 'readlines/sort'
15
15
  require_relative 'readlines/split'
16
+ require_relative 'readlines/filter'
16
17
  require 'fileutils'
17
18
  require 'json'
18
19
 
@@ -24,6 +25,7 @@ module Readlines
24
25
  include Readlines::Search
25
26
  include Readlines::Replace
26
27
  include Readlines::File
28
+ include Readlines::Filter
27
29
  include Readlines::Merge
28
30
  include Readlines::Info
29
31
  include Readlines::Pattern
@@ -33,12 +35,17 @@ module Readlines
33
35
  attr_reader :file_path
34
36
 
35
37
  def initialize(file_path, count: nil, split: nil)
38
+ file_path = ::File.join(Dir.pwd, file_path) unless ::File.absolute_path?(file_path)
39
+
40
+ raise Readlines::Error::MissingFilePathError, 'File not found at provided path' unless ::File.exist?(file_path)
36
41
  raise Readlines::Error::MissingFilePathError, 'You should provide a file path, e.g., "/path/to/file.txt"' if file_path.nil? || file_path.empty?
37
-
42
+
43
+
38
44
  @file_path = file_path
39
45
  @count_keyword = count
40
46
  @split_delimiter = split
41
47
  end
48
+
42
49
 
43
50
  include Readlines::Count
44
51
  include Readlines::Delete
@@ -46,12 +53,14 @@ module Readlines
46
53
  include Readlines::Search
47
54
  include Readlines::Replace
48
55
  include Readlines::File
56
+ include Readlines::Filter
49
57
  include Readlines::Merge
50
58
  include Readlines::Info
51
59
  include Readlines::Pattern
52
60
  include Readlines::Sort
53
61
  include Readlines::Split
54
62
  include Readlines::Content
63
+ include Readlines::Filter
55
64
 
56
65
  # Count operations
57
66
  def line_count
@@ -220,6 +229,20 @@ module Readlines
220
229
  raise Readlines::Error::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)
221
230
  file_statistics_now()
222
231
  end
232
+
233
+ ## Replace and Delete lines from the file
234
+ def filter(value, query, operation, replacement = nil)
235
+ raise Readlines::Error::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)
236
+
237
+ processed_lines = []
238
+ ::File.foreach(@file_path) do |line|
239
+ result = apply_filter(line, value, query, operation, replacement)
240
+ processed_lines << result if result
241
+ end
242
+
243
+ ::File.write(@file_path, processed_lines.join)
244
+ processed_lines
245
+ end
223
246
 
224
247
  # Pattern operations
225
248
  def pattern_exists?(pattern)
@@ -260,4 +283,13 @@ module Readlines
260
283
  decrypt_content_now(key, encrypted_file_path)
261
284
  end
262
285
  end
263
- end
286
+
287
+ def filter(file_path, value, query, operation, replacement = nil)
288
+ processed_lines = []
289
+ File.foreach(file_path) do |line|
290
+ result = filter(line, value, query, operation, replacement)
291
+ processed_lines << result if result # Only add if result is not nil (for delete operation)
292
+ end
293
+ processed_lines
294
+ end
295
+ end
@@ -2,12 +2,34 @@
2
2
 
3
3
  module Readlines
4
4
  module Error
5
- class Error < StandardError; end
5
+ class BaseError < StandardError
6
+ def initialize(message = "An error occurred in Readlines")
7
+ super
8
+ end
9
+ end
6
10
 
7
- class NotFoundError < Error; end
11
+ class NotFoundError < BaseError
12
+ def initialize(message = "File not found.")
13
+ super
14
+ end
15
+ end
8
16
 
9
- class MissingFilePathError < Error; end
17
+ class MissingFilePathError < BaseError
18
+ def initialize(message = "File path is missing.")
19
+ super
20
+ end
21
+ end
10
22
 
11
- class InvalidUnitError < StandardError; end
23
+ class InvalidUnitError < BaseError
24
+ def initialize(message = "Invalid unit provided.")
25
+ super
26
+ end
27
+ end
28
+
29
+ class ArgumentError < BaseError
30
+ def initialize(message = "Invalid argument provided.")
31
+ super
32
+ end
33
+ end
12
34
  end
13
- end
35
+ end
@@ -0,0 +1,46 @@
1
+ # readlines/lib/readlines/readlines/filter.rb
2
+ # Replace and Delete lines from the file
3
+ require_relative 'delete'
4
+ require_relative 'replace'
5
+
6
+ module Readlines
7
+ module Filter
8
+ def apply_filter(line, value, query, operation, replacement = nil)
9
+ case query
10
+ when :start
11
+ matched = line.strip.start_with?(value.to_s)
12
+ when :body
13
+ matched = line.include?(value.to_s)
14
+ when :end
15
+ matched = line.strip.end_with?(value.to_s)
16
+ else
17
+ raise Readlines::Error::ArgumentError, "Invalid query type. Use :start, :body, or :end."
18
+ end
19
+
20
+ if matched
21
+ case operation
22
+ when :delete
23
+ return nil
24
+ when :replace
25
+ raise Readlines::Error::ArgumentError, "Replacement value is required for replace operation." if replacement.nil?
26
+
27
+ pattern = case query
28
+ when :start
29
+ /^#{Regexp.quote(value.to_s)}/
30
+ when :body
31
+ /#{Regexp.quote(value.to_s)}/
32
+ when :end
33
+ /#{Regexp.quote(value.to_s)}$/
34
+ end
35
+
36
+ return line.gsub(pattern, replacement)
37
+ else
38
+ raise Readlines::Error::ArgumentError, "Invalid operation type. Use :delete or :replace."
39
+ end
40
+ else
41
+ line
42
+ end
43
+ end
44
+ end
45
+ end
46
+
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: readlines
3
3
  version: !ruby/object:Gem::Version
4
- version: '1.5'
4
+ version: '1.6'
5
5
  platform: ruby
6
6
  authors:
7
7
  - Maven
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2024-10-29 00:00:00.000000000 Z
11
+ date: 2024-11-11 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: json
@@ -99,6 +99,7 @@ files:
99
99
  - lib/readlines/readlines/delete.rb
100
100
  - lib/readlines/readlines/error.rb
101
101
  - lib/readlines/readlines/file.rb
102
+ - lib/readlines/readlines/filter.rb
102
103
  - lib/readlines/readlines/info.rb
103
104
  - lib/readlines/readlines/merge.rb
104
105
  - lib/readlines/readlines/pattern.rb