LoginSignup
26
26

More than 5 years have passed since last update.

パスの最後のディレクトリ名・ファイル名を抽出する

Last updated at Posted at 2015-10-13

シェルを書いているときに、最後のディレクトリ名が欲しいことがあったのでメモ。
/home/hoge/piyo」というパス名があったとすると、最後の「piyo」だけを抽出したい。

hoge.sh
#!/bin/bash

DIR="/home/hoge/piyo"
str=`echo ${DIR} | awk -F "/" '{ print $NF }'`
echo ${str}
結果
$ ./hoge.sh
piyo
  • awk -F "/"のところの"/"を変えれば、他の区切り文字などにも対応できる。
  • print $(NF - 1)とすると最後から二番目の区切り位置の文字が抽出できる。(例だとhogeが抽出される)
  • print $1で最初の区切り位置の文字が抽出できる。例だと最初の区切りには何もないので何も表示されない($1「""」$2「"home"」$3「"hoge"」$4「"piyo"」

追記:
もっと簡単な方法を教えて下さいました。

str=`basename ${DIR}`
26
26
3

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