Remove blank lines with grep

后端 未结 15 1945
后悔当初
后悔当初 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:10

    Here is another way of removing the white lines and lines starting with the # sign. I think this is quite useful to read configuration files.

    [root@localhost ~]# cat /etc/sudoers | egrep -v '^(#|$)'
    Defaults    requiretty
    Defaults   !visiblepw
    Defaults    always_set_home
    Defaults    env_reset
    Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR
    LS_COLORS"
    root    ALL=(ALL)       ALL
    %wheel  ALL=(ALL)       ALL
    stack ALL=(ALL) NOPASSWD: ALL
    
    0 讨论(0)
  • 2020-12-22 18:12

    Try the following:

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

    The -e option allows regex patterns for matching.

    The single quotes around ^$ makes it work for Cshell. Other shells will be happy with either single or double quotes.

    UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with "\r\n" style line endings), whereas the above only removes files with blank lines and unix style line endings:

    grep -v -e '^[[:space:]]*$' foo.txt
    
    0 讨论(0)
  • 2020-12-22 18:13

    If you have sequences of multiple blank lines in a row, and would like only one blank line per sequence, try

    grep -v "unwantedThing" foo.txt | cat -s
    

    cat -s suppresses repeated empty output lines.

    Your output would go from

    match1
    
    
    
    match2
    

    to

    match1
    
    match2
    

    The three blank lines in the original output would be compressed or "squeezed" into one blank line.

    0 讨论(0)
  • 2020-12-22 18:14
    grep -v "^[[:space:]]*$"
    
    The -v makes it print lines that do not completely match
    
    ===Each part explained===
    ^             match start of line
    [[:space:]]   match whitespace- spaces, tabs, carriage returns, etc.
    *             previous match (whitespace) may exist from 0 to infinite times
    $             match end of line
    

    Running the code-

    $ echo "
    > hello
    >       
    > ok" |
    > grep -v "^[[:space:]]*$"
    hello
    ok
    

    To understand more about how/why this works, I recommend reading up on regular expressions. http://www.regular-expressions.info/tutorial.html

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

    I prefer using egrep, though in my test with a genuine file with blank line your approach worked fine (though without quotation marks in my test). This worked too:

    egrep -v "^(\r?\n)?$" filename.txt
    
    0 讨论(0)
  • 2020-12-22 18:19

    Keep it simple.

    grep . filename.txt
    
    0 讨论(0)
提交回复
热议问题