Delete file contents using ‘sed’


[Sed] Delete one or more lines from a file

Here is how to remove one or more lines from a file.

Syntax:

sed '{[/]<n>|<string>|<regex>[/]}d' <fileName>      
sed '{[/]<adr1>[,<adr2>][/]d' <fileName>
  • /…/=delimiters
  • n = line number
  • string = string found in in line
  • regex = regular expression corresponding to the searched pattern
  • addr = address of a line (number or pattern )
  • d = delete

Examples

Remove the 3rd line:

sed '3d' fileName.txt

Remove the line containing the string “awk”:

sed '/awk/d' filename.txt

Remove the last line:

sed '$d' filename.txt

Remove all empty lines:

sed '/^$/d' filename.txt      
sed '/./!d' filename.txt

Remove the line matching by a regular expression (by eliminating one containing digital characters, at least 1 digit, located at the end of the line):

sed '/[0-9/][0-9]*$/d' filename.txt

Remove the interval between lines 7 and 9:

sed '7,9d' filename.txt

The same operation as above but replacing the address with parameters:

sed '/-Start/,/-End/d' filename.txt

The above examples are only changed at the display of the file (stdout1= screen).

For permanent changes to the old versions (<4) use a temporary file for GNU sed using the “-i[suffix]”:

sed -i".bak" '3d' filename.txt
Advertisements

About Vaibhav

Friendly & Co-operative.

One response to “Delete file contents using ‘sed’”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: