sed + remove “#” and empty lines with one sed command

后端 未结 7 2097
旧巷少年郎
旧巷少年郎 2020-12-08 02:57

how to remove comment lines (as # bal bla ) and empty lines (lines without charecters) from file with one sed command?

THX lidia

7条回答
  •  遥遥无期
    2020-12-08 03:36

    If you're worried about starting two sed processes in a pipeline for performance reasons, you probably shouldn't be, it's still very efficient. But based on your comment that you want to do in-place editing, you can still do that with distinct commands (sed commands rather than invocations of sed itself).

    You can either use multiple -e arguments or separate commands with a semicolon, something like (just one of these, not both):

    sed -i 's/#.*$//' -e '/^$/d' fileName
    sed -i 's/#.*$//;/^$/d' fileName
    

    The following transcript shows this in action:

    pax> printf 'Line # with a comment\n\n# Line with only a comment\n' >file
    
    pax> cat file
    Line # with a comment
    
    # Line with only a comment
    
    pax> cp file filex ; sed -i 's/#.*$//;/^$/d' filex ; cat filex
    Line
    
    pax> cp file filex ; sed -i -e 's/#.*$//' -e '/^$/d' filex ; cat filex
    Line
    

    Note how the file is modified in-place even with two -e options. You can see that both commands are executed on each line. The line with a comment first has the comment removed then all is removed because it's empty.

    In addition, the original empty line is also removed.

提交回复
热议问题