How to prevent grep from printing a trailing newline?

前端 未结 3 964
失恋的感觉
失恋的感觉 2021-02-02 08:44

I am using grep to produce output that will be parsed by another program.

However, that program expects output only to be numeric or zero-bytes.

No

3条回答
  •  不思量自难忘°
    2021-02-02 09:40

    I know this is old, and tr works just as well, but I happened across this question and noticed OP stated: I am executing in sh, not bash. So nesting it into echo -n "$(grep -c pattern)" doesn't work either.

    This isn't grep or sh so much as how echo is being used. For future visitors, the only reason this didn't work is due to the double quotes around the substituted command. The following does, in fact, work even using sh.

    echo -n $(grep -c pattern)
    

    Examples:

    $ ls /dev/sd? #example of formatted output
    /dev/sda  /dev/sdc  /dev/sde  /dev/sdg  /dev/sdi  /dev/sdk
    /dev/sdb  /dev/sdd  /dev/sdf  /dev/sdh  /dev/sdj
    
    $ echo $(ls /dev/sd?) #without -n, appends \n only at the end
    /dev/sda /dev/sdb /dev/sdc /dev/sdd /dev/sde /dev/sdf /dev/sdg /dev/sdh /dev/sdi /dev/sdj /dev/sdk
    
    $ echo -n $(ls /dev/sd?) #with -n, does not append the \n, but still strips the line breaks from the string
    /dev/sda /dev/sdb /dev/sdc /dev/sdd /dev/sde /dev/sdf /dev/sdg /dev/sdh /dev/sdi /dev/sdj /dev/sdk
    
    $ echo -n "$(ls /dev/sd?)" #output when double quotes are used
    /dev/sda
    /dev/sdb
    /dev/sdc
    /dev/sdd
    /dev/sde
    /dev/sdf
    /dev/sdg
    /dev/sdh
    /dev/sdi
    /dev/sdj
    /dev/sdk
    

提交回复
热议问题