Remove blank lines with grep

后端 未结 15 1946
后悔当初
后悔当初 2020-12-22 17:51

I tried grep -v \'^$\' in Linux and that didn\'t work. This file came from a Windows file system.

相关标签:
15条回答
  • 2020-12-22 18:19

    The same as the previous answers:

    grep -v -e '^$' foo.txt
    

    Here, grep -e means the extended version of grep. '^$' means that there isn't any character between ^(Start of line) and $(end of line). '^' and '$' are regex characters.

    So the command grep -v will print all the lines that do not match this pattern (No characters between ^ and $).

    This way, empty blank lines are eliminated.

    0 讨论(0)
  • 2020-12-22 18:19

    Do lines in the file have whitespace characters?

    If so then

    grep "\S" file.txt

    Otherwise

    grep . file.txt

    Answer obtained from: https://serverfault.com/a/688789

    0 讨论(0)
  • 2020-12-22 18:20

    Using Perl:

    perl -ne 'print if /\S/'
    

    \S means match non-blank characters.

    0 讨论(0)
  • 2020-12-22 18:23

    Use:

    $ dos2unix file
    $ grep -v "^$" file
    

    Or just simply awk:

    awk 'NF' file
    

    If you don't have dos2unix, then you can use tools like tr:

    tr -d '\r' < "$file" > t ; mv t "$file"
    
    0 讨论(0)
  • 2020-12-22 18:28
    awk 'NF' file-with-blank-lines > file-with-no-blank-lines
    
    0 讨论(0)
  • 2020-12-22 18:28

    egrep -v "^\s\s+"

    egrep already do regex, and the \s is white space.

    The + duplicates current pattern.

    The ^ is for the start

    0 讨论(0)
提交回复
热议问题