40
33

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.

echo | sedなんていらなかったんだ!

Posted at

変数の置換をする時、今まで下記のようにやっていたのだが、bashには古く(96年のBash2.0以降)から置換機能(Pattern substitution)が備わっていた。

MOD_HOSTNAME=$(echo $HOSTNAME | sed -e "s/foo/bar/g")

Pattern substitutionを使えばよりコンパクトかつ低コストで事をなせる。

MOD_HOSTNAME=${HOSTNAME//foo/bar}
# 最初に該当した箇所だけを変換する場合はスラッシュ1回
MOD_HOSTNAME=${HOSTNAME/foo/bar}

timeで時間を計測したところ、無名パイプとプロセスの生成はやはりコストが高かった。

$ time echo ${HOSTNAME//./---}
MacBookProRetina---local

real  0m0.000s
user  0m0.000s
sys   0m0.000s

$ time echo $HOSTNAME | sed -e "s/\./---/g"
MacBookProRetina---local

real 0m0.003s
user 0m0.002s
sys  0m0.002s
40
33
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
40
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?