Home > Mobile >  How can I add x number of characters at the beginning of a string?
How can I add x number of characters at the beginning of a string?

Time:12-15

I'm trying to add x number of 0 at the beginning of a string, the number of characters missing is stored on $x, but how can I add them into the string?

echo "$exampleString" | sed -i 's/^/0/'

sed works just fine, but the number of 0 must be typed manually instead of getting from a calculated variable

CodePudding user response:

You could use printf as such:

x=5
string="test"
printf '%0*d%s\n' "$x" 0 "$string"```

CodePudding user response:

Here is a simple loop to calculate this. Each step in the loop prepends a 0 to the result.

#!/bin/bash

text='example'
x=5
i=0
prefix='0'
until [ $i -eq $x ]; do 
  text="${prefix}${text}";
  ((i  ))
done

echo "text is: $text"
  • Related