Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

piping seq to printf for number formatting

I'm trying to print the following pattern using printf and seq:

0000
0001
0002
0003

My problem is once I use:

seq 0 10 | xargs printf %04d

all my output is formatted into the same line likeso:

0000000100020003

I still can't get the hang of using xargs. How do I use it correctly in this case?

like image 454
Paolo Avatar asked Oct 02 '13 23:10

Paolo


People also ask

Can you pipe to printf?

Redirecting and piping the output By default, printf will send the outputs to stdout (terminal). You can redirect the output to a file using the redirection operator or combine it with the pipe operator for further processing.

What is the printf command used for?

2.3. 1 C standard output (printf(), puts() and putchar()) The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.

Does printf work in Linux?

“printf” command in Linux is used to display the given string, number or any other format specifier on the terminal window. It works the same way as “printf” works in programming languages like C. Note: printf can have format specifiers, escape sequences or ordinary characters.


1 Answers

The printf command does not output a line break if you don't ask it to. Try:

seq 0 10 | xargs printf '%04d\n'

Note that you can achieve the same with just seq, since it allows specifying a printf-style format:

seq -f %04g 0 10
like image 156
Joni Avatar answered Oct 04 '22 01:10

Joni