printf command in Linux with Examples

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.

Syntax:

$printf [-v var] format [arguments]

Note: printf can have format specifiers, escape sequences or ordinary characters.

Format Specifiers: The most commonly used printf specifiers are %s, %b, %d, %x and %f.

Examples:



  • %s specifier: It is basically a string specifier for string output.
    $printf "%s\n" "Hello, World!"
    

    Output:

  • %b specifier: It is same as string specifier but it allows us to interpret escape sequences with an argument.
    Input:  printf "%s\n" "Hello, World! \n" "From Geeks For Geeks\n"
    
    Output: Hello, World! \n
            From Geeks For Geeks\n
    

    Note: The escape sequence “\n” in the above lines has no special meaning when used with “%s” specifier and is treated just like other characters. If we replace “%s” with “%b“, Then it will be interpreted as a newline character.

    Input :  printf "%b\n" "Hello, World! \n" "From Geeks For Geeks\n"
    Output:  Hello, World! 
    
             From Geeks For Geeks 
    
    

    Example:

    $printf "%b\n" "Geeks" "for" "\nGeeks\n"
    

    Output:

  • %d specifier: It is an integer specifier for showing the integral values.
    $printf "%d\n" "213" "109"
    

    Output:

  • %f specifier: It is used for output of floating point values.
    $printf "%f\n" "1.32" "3.14"
    

    Output:

  • %x specifier: It is used for output of lowercase hexadecimal values for integers and for padding the output.
    $printf "%08x\n" "1024"
    

    Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.