As a programmer or developer, it’s common to encounter files with empty lines that need to be removed for better readability and code organization. While manually removing empty lines can be a tedious and time-consuming task, there are several techniques and tools available to streamline the process.

Advertisement

In this article, we’ll explore the most effective ways to delete empty lines from files, making your file editing process faster and more efficient.

Delete Empty Lines from a File

Command-line tools are a powerful and flexible solution for automating file editing tasks. To remove empty lines using command-line tools, you can use the following commands:

Method 1: Using sed

Sed is an stream editor. We can easily remove all blank lines using sed command. Use one of following sed command to remove blank lines from file. For example main.txt is your original file from which you need to remove blank lines.

Below command will remove all blank line and save content in second file out.txt. It will not affect the original file.

sed '/^$/d' main.txt > out.txt 

Now if you want to make changes in original file using -i switch sed command.

sed -i '/^$/d' main.txt 
    -i ( edit files in place ) Used for make changes in same file.

Method 2 – Using perl

Instead of sed, you can also use perl (a programming language) to remove blank lines. Use the below example command to remove blank lines from main.txt file.

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

Method 3 – Using awk

Also you can use AWK command line tool to remove blank lines from a file. For example use below command.

awk 'NF > 0' main.txt > out.txt 

These commands remove all empty lines from the file and save the modified file to a new file. While these tools require some knowledge of the command line, they offer a fast and efficient way to remove empty lines from files.

Conclusion

In conclusion, removing empty lines from files is a necessary task for improving readability and code organization. While manual deletion is suitable for small files, regular expressions, command-line tools, and IDE features offer faster and more efficient solutions for larger files. By using these techniques, you can streamline your file editing process and spend more time focusing on your code’s functionality.

Share.

1 Comment

  1. # perl -i -n -e “print if /S/” main.txt
    not working for me

    # perl -i -n -e “print unless /^$/” main.txt

Leave A Reply


Exit mobile version