0

I have a script that needs to format numbers with thousands separators. So 1234567 becomes 1,234,567. I use printf "%'d" 1234567 to get the result. Works fine. Later in the script I set a custom IFS="," to process a table of string pairs. If I then use the printf "%'d" function I don't get commas, I get spaces instead. If I reset IFS back to its default, then printf behaves as expected. Why is IFS affecting the printf formating?

1
  • I deleted a "thank you" comment from you here. If my answer below resolves your issue, you have the option to "accept" the answer. Accepting an answer marks the issue as resolved. Please see unix.stackexchange.com/help/someone-answers Commented Feb 21, 2023 at 18:29

1 Answer 1

2

So, this is probably what's happening, or something similar to this (with a non-POSIX locale like en_US.UTF-8). The important bit is the lack of quoting when using $var below:

$ printf "%'d\n" 1234567
1,234,567
$ var=$(printf "%'d\n" 1234567)
$ echo $var
1,234,567
$ IFS=,
$ echo $var
1 234 567

Since the variable $var is used unquoted, the shell will split the variable's value on the characters in $IFS, creating separate arguments from each (the shell would also perform filename globbing on each generated word, but that is not an issue in this instance). The echo utility will print its arguments with spaces in-between them and a newline at the end.

You need to quote the expansion of variables and command substitutions. Below, I also show how to "print into a variable" with printf:

$ printf -v var "%'d" 1234567
$ printf '%s\n' "$var"
1,234,567
$ IFS=,
$ printf '%s\n' "$var"
1,234,567

Related:

2
  • or similarly somecommand $(printf...) directly without the var Commented Feb 21, 2023 at 18:12
  • 1
    @ilkkachu Yep, although seeing commas replaced by spaces indicates looking at output possibly produced by echo, but we are not certain as there is no code in the question. Commented Feb 21, 2023 at 18:19

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.