0

I need to trim the top 5 rows and the last row of my csv using a Unix command that I can run in a shell script.

I currently have head -n -1 file.csv | tail -n +6 file.csv > newfile.csv this outputs a new csv starting from row 6 which is what I need however the first part of the command fails as illegal line count -- -1

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
slackerr
  • 11
  • 1
  • 3

2 Answers2

0

I first done tail -n +6 file.csv to remove the first 5 rows.

Then to remove the last row of the csv i had to flip the csv so the last row was at the top I done this by using the tail -r command.

I then used the same command from the start to remove the now first row tail -n +2 and finally flipped the csv back using the tail -r command.

tail -n +11 input.csv | tail -r | tail -n +2 | tail -r > output.csv

slackerr
  • 11
  • 1
  • 3
0

Since you only need to delete the last line (and the first five), you can use sed far more simply:

sed -e '1,5d; $d' file.csv

Literally: delete lines 1 through 5; delete the last line.

If you needed to delete more than one line at the end, this would not work; sed doesn't generally support relative motions like $-4. In that case, I'd probably use ed or ex:

{ echo '1,5d'; echo '$-4,$d'; echo 'w'; echo 'q'; } | ed file.csv

Delete lines 1,5; delete from four lines before the last to the last (removing 5 lines at the end); write the file; quit (where the quit is optional but the write isn't).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278