0

When I executed the sed command below, it returned the expression error as follows.

user% sed -e '$-3,$d' sample.csv
sed: -e expression #1, char 2: unknown command: `-'

What I wanted to do is to delete last 4 lines from the specified file. And I found some web-sites introducing the method above, but it did not work on my environment of Mac OSX 10.9 and CentOS. How can I fix this problem?

  • 2
    possible duplicate of [how to use sed to remove last n lines of a file](http://stackoverflow.com/questions/13380607/how-to-use-sed-to-remove-last-n-lines-of-a-file) – fedorqui Jun 02 '14 at 09:56

2 Answers2

2

If you want to delete last four lines in your file then try the below command,

tac file.csv | sed '1,4d' | tac > newfile.csv
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • `tac file.csv | tail +4 | tac > newfile.csv` should be "faster". Does not have `head` an option for that (not on my AIX but maybe a `head +4` exist on Linux and derivate) – NeronLeVelu Jun 02 '14 at 11:53
1

This might work for you (GNU sed):

sed '1{N;N};N;$d;P;D' file

or the more adaptable:

sed ':a;$d;N;s/\n/&/4;Ta;P;D' file
potong
  • 55,640
  • 6
  • 51
  • 83