Search code examples
bashpipeprintfzsh

How do I pipe into printf?


I'm going nuts trying to understand what is the problem with this simple example (zsh or bash):

echo -n "6842" | printf "%'d"

The output is 0... why though? I'd like the output to be 6,842

Thanks in advance, I've had no luck for an hour now using google trying to figure this out...!


Solution

  • printf doesn't read arguments to format from standard input, but from the command line directly. For example, this works:

    $ printf "%'d" 6842
    6,842
    

    You can convert output of a command to command-line arguments using command substitution, using either backtick-based `...command...` or the more modern $(...command...) syntax:

    $ printf "%'d" $(echo -n 6842)
    6,842
    

    If you want to invoke printf inside a pipeline, you can use xargs to read input and execute printf with the appropriate arguments:

    echo -n "6842" | xargs printf "%'d"