Remove empty lines in a text file via grep

后端 未结 11 1598
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 23:17

FILE:

hello

world

foo

bar

How can I remove all the empty new lines in this FILE?

Output of command:

相关标签:
11条回答
  • 2020-12-12 23:50

    Here is a solution that removes all lines that are either blank or contain only space characters:

    grep -v '^[[:space:]]*$' foo.txt
    
    0 讨论(0)
  • 2020-12-12 23:51

    grep . FILE


    (And if you really want to do it in sed, then: sed -e /^$/d FILE)

    (And if you really want to do it in awk, then: awk /./ FILE)

    0 讨论(0)
  • 2020-12-12 23:52

    grep '^..' my_file

    example

    THIS
    
    IS
    
    THE
    
    FILE
    
    EOF_MYFILE
    

    it gives as output only lines with at least 2 characters.

    THIS
    IS
    THE
    FILE
    EOF_MYFILE
    

    See also the results with grep '^' my_file outputs

    THIS
    
    IS
    
    THE
    
    FILE
    
    EOF_MYFILE
    

    and also with grep '^.' my_file outputs

    THIS
    IS
    THE
    FILE
    EOF_MYFILE
    
    0 讨论(0)
  • 2020-12-12 23:52

    If you want to know what the total lines of code is in your Xcode project and you are not interested in listing the count for each swift file then this will give you the answer. It removes lines with no code at all and removes lines that are prefixed with the comment //

    Run it at the root level of your Xcode project.

    find . \( -iname \*.swift \) -exec grep -v '^[[:space:]]*$' \+ | grep -v -e '//' | wc -l
    

    If you have comment blocks in your code beginning with /* and ending with */ such as:

    /*
     This is an comment block 
    */
    

    then these will get included in the count. (Too hard).

    0 讨论(0)
  • 2020-12-12 23:54

    Perl might be overkill, but it works just as well.

    Removes all lines which are completely blank:

    perl -ne 'print if /./' file
    

    Removes all lines which are completely blank, or only contain whitespace:

    perl -ne 'print if ! /^\s*$/' file
    

    Variation which edits the original and makes a .bak file:

    perl -i.bak -ne 'print if ! /^\s*$/' file
    
    0 讨论(0)
  • 2020-12-12 23:56

    If removing empty lines means lines including any spaces, use:

    grep '\S' FILE
    

    For example:

    $  printf "line1\n\nline2\n \nline3\n\t\nline4\n" > FILE
    $  cat -v FILE
    line1
    
    line2
    
    line3
    
    line4
    $  grep '\S' FILE
    line1
    line2
    line3
    line4
    $  grep . FILE
    line1
    line2
    
    line3
    
    line4
    

    See also:

    • How to remove empty/blank lines (including spaces) in a file in Unix?
    • How to remove blank lines from a file in shell?
    • With sed: Delete empty lines using sed
    • With awk: Remove blank lines using awk
    0 讨论(0)
提交回复
热议问题