LoginSignup
0
0

シェル(bash)で0埋めする方法

Posted at

環境

  • OS : CentOS Linux release 8.5.2111
  • bash : GNU bash, バージョン 4.4.20(1)-release (x86_64-redhat-linux-gnu)
実行結果
[root@centos85 work]# cat /etc/redhat-release
CentOS Linux release 8.5.2111
[root@centos85 work]# bash --version
GNU bash, バージョン 4.4.20(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
ライセンス GPLv3+: GNU GPL バージョン 3 またはそれ以降 <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
[root@centos85 work]#

1. printfを使って0埋め

1.1. 「512」の数字に対して、前ゼロ埋めして10桁で表示する場合

printf "%010d" 512

実行結果
[root@centos85 work]# printf "%010d" 512
0000000512[root@centos85 work]#

1.2. 「512」の数字に対して、前ゼロ埋めして10桁で表示する場合(改行が欲しい場合)

printf "%010d\n" 512

実行結果
[root@centos85 work]# printf "%010d\n" 512
0000000512
[root@centos85 work]#

1.3. 「512」の数字に対して、前ゼロ埋めして10桁を変数に代入

IN_NUM=512
OUT_NUM=`printf "%010d" "${IN_NUM}"`
echo ${OUT_NUM}
実行結果
[root@centos85 work]# IN_NUM=512
[root@centos85 work]# OUT_NUM=`printf "%010d" "${IN_NUM}"`
[root@centos85 work]# echo ${OUT_NUM}
0000000512
[root@centos85 work]#

2. Bashの変数参照機能を使う

2.1. 「512」の数字に対して、前ゼロ埋めして10桁で表示する場合

IN_NUM=512
TMP_NUM="0000000000${IN_NUM}"
echo "${TMP_NUM: -10}"
実行結果
[root@centos85 work]# IN_NUM=512
[root@centos85 work]# TMP_NUM="0000000000${IN_NUM}"
[root@centos85 work]# echo "${TMP_NUM: -10}"
0000000512
[root@centos85 work]#

2.2. 「512」の数字に対して、前ゼロ埋めして10桁を変数に代入

IN_NUM=512
TMP_NUM="0000000000${IN_NUM}"
OUT_NUM="${TMP_NUM: -10}"
echo ${OUT_NUM}
実行結果
[root@centos85 work]# IN_NUM=512
[root@centos85 work]# TMP_NUM="0000000000${IN_NUM}"
[root@centos85 work]# OUT_NUM="${TMP_NUM: -10}"
[root@centos85 work]# echo ${OUT_NUM}
0000000512
[root@centos85 work]#

3. その他

3.1. for文で1から10を2桁(出力される数値の最大桁数)で表示

for i in $(seq -w 1 10);do echo ${i};done

実行結果
[root@centos85 work]# for i in $(seq -w 1 10);do echo ${i};done
01
02
03
04
05
06
07
08
09
10
[root@centos85 work]#

3.2. seqコマンドで1から10を0埋め10桁で表示

seq -f '%010g' 1 10

実行結果
[root@centos85 work]# seq -f '%010g' 1 10
0000000001
0000000002
0000000003
0000000004
0000000005
0000000006
0000000007
0000000008
0000000009
0000000010
[root@centos85 work]#

3.2. seqコマンドで「512」を0埋め10桁で表示

seq -f '%010g' 512 512

実行結果
[root@centos85 work]# seq -f '%010g' 512 512
0000000512
[root@centos85 work]#

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0