Home » Unix command and scripts » How to use sed to remove comments and blank lines

How to use sed to remove comments and blank lines

As an administrator on the Unix system, we may encounter situations where we must remove the blank lines from many files. Similar is the case comments also, we may need to remove from a lot of files. Doing this using vi or nano editor is going to be lengthy and very tedious. This is also very error-prone. We can achieve this using the sed command very easily. Let’s explore how we can do that

How to delete the blank lines using sed

We can use the below command

sed  '/^$/d'  < file name> 

The above will not touch the file, it will provide the output with the blank lines

Example
$cat test.txt
aaaaa

bbbb

CCCCC
ddddd
$sed  '/^$/d' test.txt
aaaaa
bbbb
CCCCC
ddddd

Now if we want to remove the blank lines from the file itself

sed  -i  '/^$/d'  < file name> 

The above command will change the file itself

Example 
 $cat test.txt 
aaaaa 

bbbb 

CCCCC 
ddddd 
$sed -i  '/^$/d' test.txt
$cat test.txt
aaaaa
bbbb
CCCCC
ddddd

We can change multiple files also using the same command.

sed  -i  '/^$/d'  *txt

How to backup the files before deleting the blank lines

This can be done using the command

sed -i.bak '/^$/d'  *txt
  • This will make a backup of all the files with the “.bak” extension before changing it
  • Remember there is no space after i
See also  How to use grep command in Unix and Linux with examples

How to remove comment using sed

This can be done using the below command

sed -i '/^#//'  < file name> 
Example   
$cat test.txt  
#aaaaa
bbbb  
CCCCC 
#ddddd  
$sed -i  '/^#//' test.txt 
$cat test.txt 
aaaaa 
bbbb 
CCCCC 
ddddd

How to remove the commented lines  from the file

This can be done using the below command

sed -i 's/#.*//' <file name>

Example   
$cat test.txt  
#aaaaa
bbbb  
CCCCC 
#ddddd  
$sed -i  '/#.*//' test.txt 
$cat test.txt 

bbbb 
CCCCC 

$

How to delete the commented and blank lines

We can achieve this using d in sed

sed -i '/^#\|^$/d' <file name>

Example   
$cat test.txt  
#aaaaa
bbbb  
CCCCC 

#ddddd  
$sed -i  '/^#\|^$/d' test.txt 
$cat test.txt 
bbbb 
CCCCC 
$

Hope you like this article

Related Articles
sed command in unix
sed replace string in file

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top