Using a bash script, I need to print to the terminal a string that uses a variable that's storing a number, but for the variable to print with comma separation if it needs it.
So for example, if I had a variable with a value of 1000, I would want to print to the terminal something like:
"Count is equal to 1,000"
I'm trying to figure out if I can do this with a single printf command. Is there a formatting option for printf that can do this, or is there a way to manipulate the variable such that I can turn it into a string with comma separation?
Try this:
printf "%'d" $MYVAR
If you need a new line at the end, do:
printf "%'d\n" $MYVAR
All together:
printf "Count is equal to %'d\n" $MYVAR
If you're on a Mac, you might need to install coreutils
. I'd suggest doing that with Homebrew : brew install coreutils
.
Per @KamilCuk, it's important to note that comma/decimal separation with numbers is based on your localization. If you'd like to change that, you can do so per this answer: https://stackoverflow.com/a/12845640/6246128
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.