bash 스크립트에서 2023-5-24 를 2023-05-24 와 같이 0을 채운 문자열을 만들고 싶었다.

$ printf
printf: usage: printf [-v var] format [arguments]

printf 명령어를 사용하면 된다.

#!/usr/bin/bash

year=2023
month=5
day=24

printf "%d-%02d-%02d" $year $month $day

형식 문자열 뒤에 변수들을 나열하면 된다.

#!/usr/bin/bash

year=2023
month=5
day=24

printf -v result "%d-%02d-%02d" $year $month $day

echo $result

변수로 저장하고 싶으면 printf -v 를 사용한다.

출처 : https://stackoverflow.com/questions/8789729/how-to-zero-pad-a-sequence-of-integers-in-bash-so-that-all-have-the-same-width

 

How to zero pad a sequence of integers in bash so that all have the same width?

I need to loop some values, for i in $(seq $first $last) do does something here done For $first and $last, I need it to be of fixed length 5. So if the input is 1, I need to add zeros in front...

stackoverflow.com

 

728x90

+ Recent posts