Hi ,
I am receiving a CSV file that can vary in number of rows each time.
I am supposed to split this file into 3 separate files like this:
- create a file named 'File1.csv' that will contain first 3 rows of the input file
- create file named 'File2.csv' that will contain last 3 rows of the input file
- create a file named 'File3.csv' that will contain all rows from the input file, except for the first 3 and last 3 rows
Can you please help me with this?
Thanks!
This sure sounds like a homework assignment to me...
Homework has special rules.
Thread reopened.
awk 'FNR==NR{lc1=FNR;next}
FNR<=3{print > "file1.csv";next}
FNR>(lc1-3){print > "file3.csv";next}
{print > "file2.csv"}' file file
rdrtx1
5
wc -l infile | read l m
awk -v l=$l '
NR <=3 {print $0 > "File1.csv"; next;}
NR >=l-2 {print $0 > "File3.csv"; next;}
{print $0 > "File2.csv";}
' infile
I think this puts the last 4 lines of file in file3.csv; not the last 3 lines. I believe the line writing file3.csv needs to be one of the following:
FNR>(lc1-3){print > "file3.csv";next}
or
FNR>=(lc1-2){print > "file3.csv";next}
Oops...typo....corrected.
RudiC
8
looping through infile only once:
awk 'NR<=3 {print >"file1.csv"; next}
{A[++i%4]=$0; j=(i+1)%4; if (A[j]) print A[j]>"file3.csv"}
END {i++; for (j=1;j<=3;j++) print A[++i%4]>"file2.csv"}
' infile