Blog

03/06/2019

Linux / Unix: Shell Remove Empty Lines



I am a new Linux user. I have text files with lots of empty lines. How do I delete all empty lines under Linux or Unix operating systems?

You can use any one of the following utility to delete all empty lines from text file:

[a] sed command

[b] awk command

[c] perl command

Syntax

The syntax is:

command input.txt > output.txt
 
command [option] input.txt > output.txt
 
sed '...' input.txt > output.txt
 
## Gnu/sed
sed -i '...' input.txt 
 
awk '...' input.txt > output.txt

sed command examples

Type the following sed command to delete all empty files:

sed '/^$/d' input.txt > output.txt
cat output.txt

OR

sed -i '/^$/d' input.txt 
cat input.txt

awk command examples

Type the following awk command to delete all empty files:

awk 'NF > 0' input.txt > output.txt
cat output.txt

perl command examples

Type the following perl one liner to delete all empty files and save orignal file as input.txt.backup:

perl -i.backup -n -e "print if /S/" input.txt

Verify updated files, type:

cat input.txt
cat input.txt.backup

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...