如何在Bash中筛选Skeet值处于150-240范围内的行?
Got it, let's figure out how to filter your 20k-line text file to only keep rows where the "Skeet" value falls between 150 and 240. Since we're dealing with a large file, we'll use methods that read line-by-line to avoid loading the entire file into memory—super efficient and straightforward.
Solution 1: Python (cross-platform, easy to tweak)
Python is perfect here because it handles large files gracefully with line-by-line iteration. Here's a script that does exactly what you need:
# Open input and output files (uses context managers to auto-close them) with open("your_input_file.txt", "r") as infile, open("filtered_output.txt", "w") as outfile: # Optional: Keep the header if your file has one (remove this block if no header) header = infile.readline() outfile.write(header) # Loop through every line in the input file for line in infile: # Clean up the line and split into columns (adjust delimiter to match your file) # Use split(" ") if columns are space-separated, split("\t") for tabs, etc. columns = line.strip().split(",") # Make sure we can safely get the Skeet value and convert it to a number try: # Replace index 2 with the actual position of your Skeet column (0-based) skeet_value = int(columns[2]) # Check if value is within the desired range (inclusive) if 150 <= skeet_value <= 240: outfile.write(line) except (IndexError, ValueError): # Skip lines that don't have the Skeet column or have invalid values continue
Notes for Python:
- Adjust the
splitdelimiter to match your file's format (comma, space, tab, etc.) - Change the index
columns[2]to match where your Skeet column is (remember Python uses 0-based indexing—so first column is 0, second is 1, etc.) - The
try/exceptblock ensures we skip any malformed lines that would crash the script.
Solution 2: Bash/Awk (fast for Linux/macOS)
If you're on a Unix-like system, Awk is a lightning-fast tool for text processing. This one-liner will do the job without writing a full script:
# Replace $3 with your Skeet column number (1-based indexing here) # Use -F ',' if your columns are comma-separated; remove -F for spaces/tabs awk -F ',' '$3 >= 150 && $3 <= 240' your_input_file.txt > filtered_output.txt
Notes for Awk:
- Awk uses 1-based indexing, so if Skeet is the third column, use
$3 - The
-F ','flag sets the field separator to a comma—adjust this if your file uses a different delimiter (like-F '\t'for tabs) - The command automatically writes all matching lines to
filtered_output.txt
Both methods will handle your 20k-line file easily—no issues with memory since they process one line at a time. Pick whichever fits your environment best!
内容的提问来源于stack exchange,提问作者Shred

