top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to remove blank lines from a file using shell script or unix command?

+2 votes
988 views
How to remove blank lines from a file using shell script or unix command?
posted Jun 8, 2015 by Amit Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

Unix Command:
$ grep -v '^$' File_Name > Temp_File | mv Temp_File File_Name

1) By grep option you can search the pattern of blank lines, i.e. '^$'
2) by -v option is takes a negation of the patter which you are searching by grep command.

$ grep -v '^$' File_Name > Temp_File

So, by above command you are identifying Non-Duplicate lines from your file and writing it to a Temp_File.

After that by piping command you are moving the data from your Temp_File to your Original File and hence your output would be achieved.

If you like my answer please vote on me....thanks...

Hope it helps you....
Arif

answer Jul 28, 2015 by Arif Shaikh
Wonderful my +1 :)
0 votes

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

answer Jun 11, 2015 by Manikandan J
Similar Questions
+2 votes

I am using below script to validate IPV6 address but this script also pass invalid IP such as empty string, name etc.

if [[ "$IPv6ADDR"=~"^:?([a-fA-F0-9]{1,4}(:|.)?){0,8}(:|::)?([a-fA-F0-9]{1,4}(:|.)?){0,8}$" ]]; then
  echo "valid ipv6 addr"
  break;
else
  echo "Invalid IP Address"
  break;
fi

Can someone identify what's wrong in the regex, Please?

+1 vote

I have some unique requirement, where I need to do something like this -
1. My script takes the argument as file name which is absolute filename.
2. I need to separate the filename and directory from this absolute file name for the further processing.

Any suggestions -

...