Remove empty lines in a text file via grep

后端 未结 11 1599
佛祖请我去吃肉
佛祖请我去吃肉 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-13 00:01

    Try this: sed -i '/^[ \t]*$/d' file-name

    It will delete all blank lines having any no. of white spaces (spaces or tabs) i.e. (0 or more) in the file.

    Note: there is a 'space' followed by '\t' inside the square bracket.

    The modifier -i will force to write the updated contents back in the file. Without this flag you can see the empty lines got deleted on the screen but the actual file will not be affected.

    0 讨论(0)
  • 2020-12-13 00:02
    with awk, just check for number of fields. no need regex
    
    $ more file
    hello
    
    world
    
    foo
    
    bar
    
    $ awk 'NF' file
    hello
    world
    foo
    bar
    
    0 讨论(0)
  • 2020-12-13 00:02

    Try ex-way:

    ex -s +'v/\S/d' -cwq test.txt
    

    For multiple files (edit in-place):

    ex -s +'bufdo!v/\S/d' -cxa *.txt
    

    Without modifying the file (just print on the standard output):

    cat test.txt | ex -s +'v/\S/d' +%p +q! /dev/stdin
    
    0 讨论(0)
  • 2020-12-13 00:02

    Simplest Answer -----------------------------------------

    [root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
    Defaults   !visiblepw
    Defaults    always_set_home
    Defaults    match_group_by_gid
    Defaults    always_query_group_plugin
    Defaults    env_reset
    Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
    Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
    Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
    Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
    Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
    Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
    root    ALL=(ALL)       ALL
    %wheel  ALL=(ALL)       ALL
    [root@node1 ~]#
    
    0 讨论(0)
  • 2020-12-13 00:04

    Try the following:

    grep -v -e '^$'
    
    0 讨论(0)
提交回复
热议问题