sed join lines together

后端 未结 5 1606
面向向阳花
面向向阳花 2020-11-28 09:14

what would be the sed (or other tool) command to join lines together in a file that do not end w/ the character \'0\'?

I\'ll have lines like this

5条回答
  •  半阙折子戏
    2020-11-28 09:55

    The rating of this answer is surprising ;s (this surprised wink emoticon pun on sed substitution is intentional) given the OP specifications: sed join lines together.

    This submission's last comment

    "if that's the case check what @ninjalj submitted"

    also suggests checking the same answer.

    ie. Check using sed ':a;/0$/{N;s/\n//;ba}' verbatim

    sed ':a;/0$/{N;s/\n//;ba}'
     does
     no one
     ie. 0
     people,
     try
     nothing,
    
     ie. 0
     things,
     any more,
     ie. 0
     tests?
    
              (^D aka eot 004 ctrl-D ␄  ... bash generate via: echo ^V^D)
    

    which will not give (do the test ;):

     does no one ie. 0
     people, try nothing, ie. 0
     things, any more, ie. 0
     tests?          (^D aka eot 004 ctrl-D ␄  ... bash generate via: echo ^V^D)
    

    To get this use:

    sed 'H;${z;x;s/\n//g;p;};/0$/!d;z;x;s/\n//g;'
    

    or:

    sed ':a;/0$/!{N;s/\n//;ba}'
    

    not:

    sed ':a;/0$/{N;s/\n//;ba}'
    

    Notes:

    sed 'H;${x;s/\n//g;p;};/0$/!d;z;x;s/\n//g;'
    

    does not use branching and
    is identical to:

    sed '${H;z;x;s/\n//g;p;};/0$/!{H;d;};/0$/{H;z;x;s/\n//g;}'
    
    • H commences all sequences
    • d short circuits further script command execution on the current line and starts the next cycle so address selectors following /0$/! can only be /0$/!! so the address selector of
      /0$/{H;z;x;s/\n//g;} is redundant and not needed.
    • if a line does not end with 0 save it in hold space
      /0$/!{H;d;}
    • if a line does end with 0 save it too and then print flush (double entendre ie. purged and lines aligned)
      /0$/{H;z;x;s/\n//g;}
    • NB ${H;z;x;s/\n//g;p;} uses /0$/ ... commands with an extra p to coerce the final print and with a now unnecessary z (to empty and reset pattern space like s/.*//)

提交回复
热议问题