How can I redirect fixed lines to a new file with shell

88 views Asked by At

I know we can use > to redirect IO to a file. While I want to write fixed line to a file.

For example,

more something will output 3210 lines, then I want

line 1~1000 in file1

line 1001~2000 in file2

line 2001~3000 in file3

line 3001~3210 in file4.

How can I do it with SHELL script?

Thx.

1

There are 1 answers

0
jonathadv On BEST ANSWER

The split command is what you need.

split -l 1000 your_file.txt "prefix"

Where:

-l - split in lines.

1000 - The number of lines to split.

your_file.txt - The file you want to split.

prefix - A prefix to the output files' names.

Example for a file of 3210 lines:

# Generate the file
$ seq 3210 > your_file.txt

# Split the file
$ split -l 1000 your_file.txt "prefix"

# Check the output files' names
$ ls prefix*
prefixaa  prefixab  prefixac  prefixad

# Check all files' ending 
$ tail prefixa*
==> prefixaa <==
991
992
993
994
995
996
997
998
999
1000

==> prefixab <==
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000

==> prefixac <==
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000

==> prefixad <==
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210