What does sed -i '1d' do?

In sed:

  • -i option will edit the input file in-place

  • '1d' will remove the first line of the input file

Example:

% cat file.txt 
foo
bar

% sed -i '1d' file.txt 

% cat file.txt        
bar

Note that, most of the time it's a good idea to take a backup while using the -i option so that you have the original file backed up in case of any unexpected change.

For example, if you do:

sed -i.orig '1d' file.txt 

the original file will be kept as file.txt.orig and the modified file will be file.txt.


1. a)

sed '1d' file.txt

Prints the contents of file.txt; excluding the first line; to the standard output.


2. a)

sed -i    '1d' file.txt # GNU, NetBSD, OpenBSD
sed -i '' '1d' file.txt # FreeBSD, macOS

Prints the contents of file.txt; excluding the first line; back into file.txt; overwriting the original.


2. b)

sed -i.back '1d' file.txt

Creates a backup of the original (as file.txt.back), before making changes. Except with FreeBSD sed, the suffix (here .back) must be attached to the -i option (in the same argument, no space between -i and .back).


3. a)

sed '2d' file.txt

Prints the contents of file.txt; excluding the second line; to the standard output.
(Specifying any number will remove the corresponding line).

Also compatible with the -i flag.


3. b)

sed '1!d' file.txt

Prints the contents of file.txt; excluding all but the first line; to the standard output.
(In other words; only the first line gets printed).

Also compatible with the -i flag.


3. c)

sed '$d' file.txt

Prints the contents of file.txt; excluding the last line; to the standard output.

Also compatible with the -i flag.


In sed -h have:

  -i[SUFFIX], --in-place[=SUFFIX]
             edit files in place (makes backup if SUFFIX supplied)

and 'perform the operation on the file itself.' absolute it'is.

And man said: 'Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline).'

as your question,

sed -i '1d' file_name

means: delete the first line in file "file_name" at place and backup to file. (just like edit file and delete first line directly. )

Tags:

Sed