Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pipe into printf? [duplicate]

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...!

like image 613
Mark McCullagh Avatar asked Mar 02 '26 16:03

Mark McCullagh


1 Answers

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"
like image 78
user4815162342 Avatar answered Mar 05 '26 07:03

user4815162342