How do I pipe into printf? [duplicate]
Asked Answered
F

2

10

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

Flavone answered 28/2, 2021 at 20:14 Comment(0)
T
25

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:

$ 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"
Traction answered 28/2, 2021 at 20:22 Comment(0)
P
6

printf does not format data passed to it on standard input; it takes a set of arguments, the first of which is the format, and the remainder are the values to display.

Luckily, this is exactly what xargs is for; to quote the manual:

xargs - build and execute command lines from standard input

So instead of piping to printf directly, you can pipe to xargs, and tell it to run printf for you with the given arguments. In short:

echo -n "6842" | xargs printf "%'d"
Prowler answered 28/2, 2021 at 20:24 Comment(1)
Thank you as well, glad to see the consensus ;)Flavone

© 2022 - 2024 — McMap. All rights reserved.