Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Linux Commands»How to Remove Empty Lines from File

    How to Remove Empty Lines from File

    By RahulJuly 8, 20132 Mins Read

    Some time we need to remove empty lines from a file. Its can be done manually if file have few lines but if file have thousands of line this is hard to be done manually. Use one of following method to remove empty lines from a file.

    Advertisement

    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 seconf 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 languege) 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
    

    files
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Split Command in Linux With Examples (Split Large Files)

    Test Your Internet Speed from the Linux Terminal

    11 Practical Example of cat Command in Linux

    View 1 Comment

    1 Comment

    1. frank on March 21, 2019 5:40 pm

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

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

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to Split Large Archives in Linux using the Command Line
    • System.out.println() Method in Java: A Beginner’s Guide
    • Split Command in Linux With Examples (Split Large Files)
    • Test Your Internet Speed from the Linux Terminal
    • 11 Practical Example of cat Command in Linux
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.