Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux Shell 腳本分割大型文字檔:split + 遞迴切割實戰

編輯:關於 Linux

超大文字檔(如日誌、匯出資料)難以傳輸或編輯,需分割成小檔。本文提供兩階段分割策略:先用 split 按行數/大小粗分,再用 Shell 迴圈將每段進一步細分,並自動建立對應目錄歸檔。

第一階段:split 快速粗分

# 按行數分割(每檔 100 萬行)
split -l 1000000 bigfile.txt chunk_

# 按大小分割(每檔 100MB)
split -b 100M bigfile.txt chunk_

# 產出:chunk_aa, chunk_ab, chunk_ac ...

參數:-l 行數、-b 位元組(支援 k/m/g 後綴)。

第二階段:Shell 迴圈細分並歸檔

#!/bin/bash
bigfile="1.txt"
# 1. 先粗分 100 萬行
split -l 1000000 "$bigfile" text

currdir=1
for smallfile in $(ls | grep "^text"); do
    linenum=$(wc -l < "$smallfile")
    n1=1
    file=1
    savedir="${smallfile}${currdir}"

    # 建立對應目錄
    [ ! -d "$savedir" ] && mkdir "$savedir"

    # 迴圈細分每 1 萬行
    while [ $n1 -lt $linenum ]; do
        n2=$((n1 + 9999))
        sed -n "${n1},${n2}p" "$smallfile" > "${savedir}/text${file}.txt"
        n1=$((n2 + 1))
        file=$((file + 1))
    done

    currdir=$((currdir + 1))
done

關鍵點解析

  • split 自動產生 aa, ab, ac... 後綴,避免檔名衝突;
  • sed -n "M,Np" 精準提取行範圍,不載入整檔記憶體;
  • 目錄命名 ${smallfile}${currdir} 確保唯一性;
  • 適合單機離線處理,若需分散式處理請改用 Hadoop/Spark。

進階:單指令完成「按 1 萬行分割並存入子目錄」

#!/bin/bash
# 使用 awk 一次掃描完成分割與歸檔
awk '
    { print > sprintf("part_%03d/%06d.txt", (NR-1)/10000, (NR-1)%10000) }
' bigfile.txt
# 需先建立 part_000, part_001... 目錄

或使用 split -l 10000 --additional-suffix=.txt bigfile.txt part_ 直接產生小檔,再用腳本歸檔。

應用場景

場景推薦分割單位工具選擇
日誌分析上傳 ELK5-10 萬行split + Filebeat
資料庫匯出 CSV 導入1-5 萬行split -l
郵件附件傳輸限制20-25MBsplit -b 20M
編輯器開啟大檔1-2 萬行split -l

善用 split 與 Shell 流控制,輕鬆馭服 GB 級文字檔。

Copyright © Windows教程網 All Rights Reserved