How to split one text file into multiple *.txt files?

前端 未结 9 599
[愿得一人]
[愿得一人] 2020-12-07 17:39

I got a text file file.txt(12 MBs) containing:

something1
something2
something3
something4
(...)

Is there any way to split

相关标签:
9条回答
  • 2020-12-07 18:03

    John's answer won't produce .txt files as the OP wants. Use:

    split -b=1M -d  file.txt file --additional-suffix=.txt
    
    0 讨论(0)
  • 2020-12-07 18:05

    Using bash:

    readarray -t LINES < file.txt
    COUNT=${#LINES[@]}
    for I in "${!LINES[@]}"; do
        INDEX=$(( (I * 12 - 1) / COUNT + 1 ))
        echo "${LINES[I]}" >> "file${INDEX}.txt"
    done
    

    Using awk:

    awk '{
        a[NR] = $0
    }
    END {
        for (i = 1; i in a; ++i) {
            x = (i * 12 - 1) / NR + 1
            sub(/\..*$/, "", x)
            print a[i] > "file" x ".txt"
        }
    }' file.txt
    

    Unlike split this one makes sure that number of lines are most even.

    0 讨论(0)
  • 2020-12-07 18:07

    Try something like this:

    awk -vc=1 'NR%1000000==0{++c}{print $0 > c".txt"}' Datafile.txt
    
    for filename in *.txt; do mv "$filename" "Prefix_$filename"; done;
    
    0 讨论(0)
  • 2020-12-07 18:08

    Regardless to what is said above, on my ubuntu 16 i had to do :

    > split -b 10M -d  system.log system_split.log 
    

    Please note the space between -b and the value

    0 讨论(0)
  • You can use the linux bash core utility split

    split -b 1M -d  file.txt file 
    

    Note that M or MB both are OK but size is different. MB is 1000 * 1000, M is 1024^2

    If you want to separate by lines you can use -l parameter.

    UPDATE

    a=(`wc -l yourfile`) ; lines=`echo $(($a/12)) | bc -l` ; split -l $lines -d  file.txt file
    

    Another solution as suggested by Kirill, you can do something like the following

    split -n l/12 file.txt
    

    Note that is l not one, split -n has a few options, like N, k/N, l/k/N, r/N, r/k/N.

    0 讨论(0)
  • 2020-12-07 18:21

    If each part have the same lines number, for example 22, here my solution:
    split --numeric-suffixes=2 --additional-suffix=.txt -l 22 file.txt file
    and you obtain file2.txt with the first 22 lines, file3.txt the 22 next line…

    Thank @hamruta-takawale, @dror-s and @stackoverflowuser2010

    0 讨论(0)
提交回复
热议问题