You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按首列的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:

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 with 6, 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 6 line), 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).

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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:56:17