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.
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 -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.
Method 3 – Using awk
Also you can use AWK command line tool to remove blank lines from a file. For example use below command.
ConclusionIn 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.
1 Comment
# perl -i -n -e “print if /S/” main.txt
not working for me
# perl -i -n -e “print unless /^$/” main.txt