x
contains the number of characters to add. How can I add $x
number of characters to a text line?
sed -i s/^/ /
sed
does the job, but the number of spaces must be typed. In my case, the number of spaces is in a calculated variable.
You can use printf
with a field width specification.
line=$(printf "%*s%s" $x '' "$line")
echo "$line"
*
means to get the width from the argument $x
. Then it prints an empty string in a field with that width, and follows it with the original value of $line
.
Using awk
x=3; awk -v x="$x" '{printf "%" x "s%s\n", "", $0}' file
or
x=3; awk '{printf "%"'$x'"s%s\n", "", $0}' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With