-3

I have this command to split csv by number of rows, line= part. But this cmd does not keep headers from original file and I need to have the headers there. Can you please help me? I found that I need to keep headers separately and then somehow add the n of rows.

It loads output.csv file and splits it every 33 rows in a result file which is called output<number>.csv with numbers before the extension and starting from 1.

awk -v N=1 -v pre="output" -v suf=".csv" -v line=33 'NR%line==1{x=pre N suf ;N++} {print > x}' output.csv

How can I keep the headers and keep my functionality?

TylerH
  • 20,799
  • 66
  • 75
  • 101
sixplus4iszen
  • 311
  • 1
  • 2
  • 10

1 Answers1

1

Let's say that output.csv is

header
1a
2a
3a
1b
2b
3b
1c
2c
3c

Just fixing a little bit your code :

awk -v pre="output" -v suf=".csv" -v line=3 '
NR == 1 {
    header = $0
    next
}
NR % line == 2 {
    close(x)
    N++
    x = pre N suf
    print header > x
}
{
    print > x
}
' output.csv

Creates 3 files :

output1.csv

header
1a
2a
3a

output2.csv

header
1b
2b
3b

output3.csv

header
1c
2c
3c

Don't forget to close if you write many files.

Corentin Limier
  • 4,946
  • 1
  • 13
  • 24
  • 1
    @EdMorton I did ask myself the question! I was lazy and didn't read the link I provided entirely `close() silently does nothing if given an argument that does not represent a file, pipe, or coprocess that was opened with a redirection.` . Thank you :) – Corentin Limier Jul 16 '19 at 12:55