Marcos
Marcos

Reputation: 895

How to print "-" using printf

I am trying to print "-" multiple times using printf. I am using the below command to print the same character multiple times, which works fine for all except "-".

printf "`printf '=%.0s' {1..30}` \n"

When I try to do the same for "-", it gives error.

printf "`printf '-%.0s' {1..30}` \n"
bash: printf: -%: invalid option

It is trying to take it as user-passed option. How do I work around this?

Upvotes: 3

Views: 839

Answers (2)

glenn jackman
glenn jackman

Reputation: 246799

Are you trying to print 30 hyphens? This is how I do that:

printf "%*s\n" 30 "" | sed 's/ /-/g'

The printf command prints a line with 30 spaces, then use sed to turn them all into hyphens

This can be encapsulated into a function:

ruler() { printf "%*s\n" "$1" "" | sed "s/ /${2//\//\\\/}/g"; }

And then you can do stuff like:

ruler $(tput cols) =

Upvotes: 2

Siguza
Siguza

Reputation: 23840

Pass -- before everything else to each printf invocation:

printf -- "`printf -- '-%.0s' {1..30}` \n"

Like many commands, printf takes options in the form of tokens starting with - (although -v and -- are the only options I know). This interferes with your argument string, as printf is instead trying to parse -%.0s as an option. For that case however, it supports the -- option (like many other commands), which terminates option parsing and passes through all following arguments literally.

Upvotes: 5

Related Questions