如何按首列的6和7值拆分制表符分隔文本文件的记录?
Split Tab-Delimited Records by 6-to-7 Boundaries
Here are two practical, efficient ways to split your tab-delimited file into separate output files, where each file contains records starting with a line beginning with 6 and ending with the next line starting with 7:
Solution 1: Using Awk (Recommended)
Awk is purpose-built for this kind of text processing. This one-liner will handle the split seamlessly:
awk '/^6/{f="file"++n".txt"} f{print > f; if(/^7/) close(f)}' your_input_file.txt
How it works:
/^6/{f="file"++n".txt"}: When a line starts with6, we create a new output file name (e.g.,file1.txt,file2.txt) by incrementing a counter each time a new block starts.f{print > f; if(/^7/) close(f)}:- If we have an active output file (we’ve already found a starting
6line), write the current line to that file. - When we hit a line starting with
7, close the file to avoid hitting system limits on open files (critical if you have many blocks).
- If we have an active output file (we’ve already found a starting
Solution 2: Using a Bash Script (For Explicit Control)
If you prefer a more verbose, customizable approach, here’s a bash script that achieves the same result:
#!/bin/bash input_file="your_input_file.txt" file_counter=1 active_output="" while IFS= read -r line; do # Start a new file when we hit a line starting with 6 if [[ "$line" =~ ^6 ]]; then active_output="file${file_counter}.txt" echo "$line" > "$active_output" # Append to the active file if it exists elif [[ -n "$active_output" ]]; then echo "$line" >> "$active_output" # Close the file and increment counter when we hit a line starting with 7 if [[ "$line" =~ ^7 ]]; then file_counter=$((file_counter + 1)) active_output="" fi fi done < "$input_file"
How it works:
- We initialize a counter for output files and a variable to track the current active file.
- For each line in the input:
- If it starts with
6, we create a new output file and write the line to it. - If we have an active output file, append the line to it. When we hit a line starting with
7, we increment the counter and reset the active file variable.
- If it starts with
Verification
After running either method, you can verify the output by checking files like file1.txt—it should contain the first block of lines from your input, starting with 6 and ending with 7.
内容的提问来源于stack exchange,提问作者Bihag
相关产品推荐
相关产品推荐

