我有一个 10000 行的文件。我想在每个不同的文件中一次创建 100 行的批次。我知道这可以使用 while 循环来完成。但是,我想知道是否可以直接使用 sed 或 awk 或 head 或 tail 命令来完成
答案1
使用split
-- 这就是创建该命令的原因
split -l 100 big_file
您也可以使用 awk:
awk -v n=100 'NR%n == 1 {out = "outfile" ++c} {print > out}' big_file
答案2
Danilas-MacBook-Pro:ruby dladner$ head sample.txt
testing
testing
testing
testing
testing
testing
testing
testing
testing
testing
Danilas-MacBook-Pro:ruby dladner$ wc -l sample.txt
10000 sample.txt
Danilas-MacBook-Pro:ruby dladner$ awk 'NR%100==1{fn && close(fn);fn="FILE"++i".txt";}{print > fn}' sample.txt
Danilas-MacBook-Pro:ruby dladner$ head FILE1.txt
testing
testing
testing
testing
testing
testing
testing
testing
testing
testing
Danilas-MacBook-Pro:ruby dladner$ wc -l !$
wc -l FILE1.txt
100 FILE1.txt
Danilas-MacBook-Pro:ruby dladner$ ls FILE* | wc -l
100
Danilas-MacBook-Pro:ruby dladner$ ls FILE{1..9}.txt
FILE1.txt FILE2.txt FILE3.txt FILE4.txt FILE5.txt FILE6.txt FILE7.txt FILE8.txt FILE9.txt
TL;DR 要使用的命令:
awk 'NR%100==1{fn && close(fn);fn="FILE"++i".txt";}{print > fn}' sample.txt
答案3
尝试一下,它将创建不同的文件,每个文件包含 200 行:
count=0
filename=0
while [ $count -lt 9000 ]
do
count=$(($count + 200))
filename=$(($filename + 1))
head -$count abc.txt | tail -200 > pqr${filename}.txt
done