How do I add a newline using printf?

202,930

Solution 1

To write a newline use \n not /n the latter is just a slash and a n

Solution 2

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget
Share:
202,930
Nightlock32
Author by

Nightlock32

Updated on April 13, 2020

Comments

  • Nightlock32
    Nightlock32 about 4 years

    How do I add a new line to a print command using printf?

    printf "I want this on a new line!"
    

    I thought it would be something like this but it didn't work

    printf "/n I want this on a new line!/n"
    

    Thanks in advance for the help!

  • Nightlock32
    Nightlock32 about 12 years
    Sorry to ask another question, but is it possible to create a single command with multiple words? So for example, change the ls command to list files?
  • petschekr
    petschekr about 12 years
    You probably can't use two words with a space because it will think of it as the command "list" with the argument "files". list-files could probably be aliased. Try Googling around for terminal aliases on your OS. "ls" is shorter though and easier to remember.
  • Elijah Lynn
    Elijah Lynn over 4 years
    Thanks, I had mine unquoted and it wasn't working. Also, here is an example if you need to do a process substitution too, replace 'date' with any other command. printf "$(date) \n\n".
  • SourceSeeker
    SourceSeeker about 2 years
    @ElijahLynn: You should separate formatting from data: printf '%s\n\n' "$(date)"
  • Elijah Lynn
    Elijah Lynn about 2 years
    Nice, that is good separation, thanks!