LoginSignup
13
13

More than 5 years have passed since last update.

シェルスクリプトで文字列を分割し末尾を取得したい

Posted at

シェルスクリプトで「/home/hoge/fuga」や「/home/hoge/fuga/foo」のような文字列を「/」で分割した時の末尾の文字列(fugaとfoo)を取得してみたときのメモ

trコマンドを使う

以下で出来ました。
trコマンドで「/」を「 」に変換し、一旦配列に入れ、その後末尾を取得しました。

path="/home/hoge/fuga"

array=( `echo $path | tr -s '/' ' '`)
last_index=`expr ${#array[@]} - 1`

# print fuga
echo ${array[${last_index}]}

以下のように関数にしてみました。

function get_last_dir() {
  path=$1

  array=( `echo $path | tr -s '/' ' '`)
  last_index=`expr ${#array[@]} - 1`
  echo ${array[${last_index}]}
  return 0
}

# main
path="/home/hoge/fuga"
last_dir=`get_last_dir $path`
echo $last_dir

IFSを使ってみる

IFS(Internal Field Separator )をデフォルトの「$' ¥t¥n'」から「/」に変更して配列に格納し、その後末尾を取得します。
ちなみにdir=($path)という部分をdir=(echo $path)としていると動かなかった。。(なんでか分かってないですが。。。)

function get_last_dir() {
  path=$1

  IFS_BACKUP=$IFS
  IFS='/'
  array=($path)
  IFS=$IFS_BACKUP
  last_index=`expr ${#array[@]} - 1`
  echo ${dir[${last_index}]}
  return 0
}

# main
path="/home/hoge/fuga"
last_dir=`get_last_dir $path`
echo $last_dir
13
13
7

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
13
13