Unix script to delete first line of file on Mac

On my Mac, when I try to run:

sed -i 2d file.csv 

from the response to the Unix script, to remove the first line of the CSV file , I get the following error:

 sed: 1: "file.csv": invalid command code f 

What if I want to delete the first two lines from file.csv ?

+5
source share
2 answers

Mac BSD sed requires a backup suffix (but the suffix may be an empty string, '' ) - it is not optional, as in GNU sed . Therefore, your command is interpreted as "backing up the file with the suffix 2d and ... oops, you provided script file.csv , but f not a sed command."

 sed -i .bak -e 2d file.csv 

This removes the first row of data from the CSV file (leaving the header row in place).

If you want to write code to work with both BSD and GNU sed , you need to attach the suffix to the -i option (GNU sed requires a suffix attached to the -i option, which determines whether there is an additional suffix or not ):

 sed -i.bak -e 2d file.csv 

Note that you cannot use an empty suffix and have a command to work with both BSD sed and GNU sed .

-e optional on the command line, but I often use it. I also often quote the command in single quotes, although this is not necessary here.

If you want to delete the first two rows of data, use 2,3d as a command. If you want to delete the first two lines, use 1,2d .

If you don't need a backup, you can either delete it after the sed command completes (the easiest way), or use a two-step or three-step dance:

 sed 2d file.csv > file.csv.bak && mv file.csv.bak file.csv # Oops; there went the links sed 2d file.csv > file.csv.bak && cp file.csv.bak file.csv rm -f file.csv.bak 

In doing so, you may need to add trap commands to clear the intermediate .bak file if an interrupt or other signal completes the script.


To quote from Apple's documentation for sed - which was originally indicated by Diego in the answer that he chose to delete, the -i option takes an argument indicating the extension that will be used for backups.

-i extension

Edit files in place, saving backups with the specified extension. If the extension is specified with a zero length, the backup will not be saved. It is not recommended to specify a zero-length extension when editing files in place, since you risk flogging or partial content in situations where disk space is exhausted, etc.

+11
source

sed -i.bak '2,3d' filename.csv will delete lines 1 and 2 (if you have headers)

This command edits the referenced file while backing up the source file (hence using .bak ). Deleting the line '2,3d' will delete the second and third lines of the source file.

+2
source

All Articles