3
2

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.

bash パラメータ展開

Last updated at Posted at 2015-09-24

bash のパラメータ展開、覚えておくと意外と使えます。

パラメータ展開    内容           
${parameter#word} 先頭から前方最短一致した位置まで取り除く
${parameter##word} 先頭から前方最長一致した位置まで取り除く
${parameter%word} 末尾から後方最短一致した位置まで取り除く
${parameter%%word} 末尾から後方最長一致した位置まで取り除く
${parameter:開始位置:終端位置} 指定した開始位置から終端位置まで抜き出す

その他、$[#parameter} でparameterの文字数が取得できる

以下簡単な使用例

test.sh
#!/bin/bash

url="hogehoge@hoge.com"

echo "url        :${url}"

# domain_part の抜出
echo "domain_part:${url##*@}"

# local_part の抜出
echo "local_part :${url%%@*}"

# 開始位置、終端位置を指定しての抜出
echo "${url:0:4}"

# 文字数取得
echo ${#url}

[user@hoge script]$ sh ./test.sh
url :hogehoge@hoge.com
domain_part :hoge.com
local_part :hogehoge
hoge
17

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?