When I try the command:
n=10 ; echo "ABCD" | sed 's/^/'$(printf "%${n}s" "")'/'
on OS X El Capitan Version 10.11.6 using ksh
version 93u+ 2012-08-01 and with bash
version 3.2.57(1)-release (x86_64-apple-darwin15) I get a syntax error similar to:
sed: 1: "s/^/": unterminated substitute in regular expression
which I believe is what is required by the standards since the output of the command substitution is not quoted.
And, while it is true that some shells will manufacture an empty string argument or a zero numeric argument to match printf
format specifiers, that behavior is not required by the standards and will result in syntax errors in some shells with a built-in printf
utility and in some stand-alone implementations of the printf
utility.
Either of the following should work with any standards conforming shell, sed
, and printf
utilities:
n=10 ; echo "ABCD" | sed 's/^/'"$(printf "%${n}s" "")"'/'
or:
n=10 ; echo "ABCD" | sed 's/^/'"$(printf '%$*s' "$n" "")"'/'
or, if the string you want to print is in a variable instead of being read from standard input:
n=10; string="ABCD"; printf "%$ns%s" "" "$string"
or:
n=10; string="ABCD"; printf '%*s%s' "$n" "" "$string"
In all of these cases, as already explained, the commands:
printf '%Ns" "string"
printf '%*s" N "string"
where N is a non-negative integer will print the string specified by the last operand right justified in a field that is N characters wide with leading space fill. If the string specified by the last operand is more than N characters, it will not be truncated. If you wanted a field of exactly 6 characters no matter how long the given string is, you can specify both a minimum and a maximum field width. And, you can also specify left justified text instead of right justified text. The following code:
printf 'X%6.6sX\n' "ABCD"
printf 'X%-6.6sX\n' "ABCD"
printf 'X%6.6sX\n' "abcdefgh"
producing the output:
X ABCDX
XABCD X
XabcdefX