3

As we can see from this Q&A, What does {0} mean when found in a string in C#?, C# uses a different approach than C/C++'s printf for String.Format, or Console.WriteLine, which allows the same parameter to be used at many places. E.g.,

String.Format("Fib: {0}, {0}, {1}, {2}, {0}", 1,  1+1, 1+2)

Is there any Linux command line printf tool that has the same benefit of allowing the same parameter to be used at many places?

Community
  • 1
  • 1
xpt
  • 20,363
  • 37
  • 127
  • 216
  • 2
    You can do this in any shell script; the arguments to the script are named $1, $2, etc, and can each be referred to multiple times. – Ernest Friedman-Hill May 03 '14 at 16:19
  • No there's no such tool commonly used, but it shouldn't be hard to create (a very simple) one: Just replace the number with the correct argument (can even be done as a simple shell-script). Allowing more complicated formats (precision and such) will be a little harder, but still very possible. – Some programmer dude May 03 '14 at 16:19
  • 1
    In addition to what @ErnestFriedman-Hill said, you can even do that in a shell function (don't necessarily need a script). – devnull May 03 '14 at 16:22
  • No standard way, so just use a function or more parameters. You do not want somebody asking on StackOverflow `what is this code doing?` keep it readible. – Walter A May 03 '14 at 20:59

1 Answers1

3

Here's a one liner, using python (it's easy to write one using other languages).

% alias myprintf='python -c "import sys; print sys.argv[1].format(*sys.argv[2:])"'
% myprintf "a {0} is a {0} is a {1}" dog cat
a dog is a dog is a cat

In the alias command, I'm assuming you're using bash.

shx2
  • 61,779
  • 13
  • 130
  • 153
  • Super cool! I realize that I can use shell function after asking the question and was ready to use it if no such too exist. – xpt May 03 '14 at 21:47