Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add x number of leading spaces in a string using Bash?

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.

like image 427
MLD Avatar asked Dec 06 '22 15:12

MLD


2 Answers

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.

like image 174
Barmar Avatar answered Mar 17 '23 01:03

Barmar


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
like image 31
slitvinov Avatar answered Mar 17 '23 01:03

slitvinov