11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sedでゼロパディングを解除(行頭のゼロを削除)する

Posted at
  • 0 -> 0
  • 0000 -> 0
  • 0102030405000 -> 102030405000
  • 00000102030405000 -> 102030405000
  • 1 -> 1
  • 12 -> 12
  • 11112222 -> 11112222

こんなような感じのゼロパディング(ゼロ埋め)解除をやりたい。

正規表現

こんな感じになった。

s/0*\([0-9]*[0-9]$\)/\1/g

\1は1個目にマッチした部分文字列を切り出すという意味らしい。
最初、行頭からマッチさせてマッチした部分を空白で置換させようとしてたのだけど、00などがくる場合の条件の書き方がわからなかった。
「マッチした部分を置換」ではなく「マッチした部分文字列の切り出し」にしたらすっきり書けた(気がする)。

実行例

$ echo 0 | sed 's/0*\([0-9]*[0-9]$\)/\1/g'
0
$ echo 0000 | sed 's/0*\([0-9]*[0-9]$\)/\1/g'
0
$ echo 0102030405000 | sed 's/0*\([0-9]*[0-9]$\)/\1/g'
102030405000
$ echo 00000102030405000 | sed 's/0*\([0-9]*[0-9]$\)/\1/g'
102030405000
$ echo 1 | sed 's/0*\([0-9]*[0-9]$\)/\1/g'
1
$ echo 12 | sed 's/0*\([0-9]*[0-9]$\)/\1/g'
12
$ echo 11112222 | sed 's/0*\([0-9]*[0-9]$\)/\1/g'
11112222

参考

11
6
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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?