2
0

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 3 years have passed since last update.

Linux: パスからファイル名、ディレクトリ名、親ディレクトリパスを切り出す方法

Posted at

たまに必要となるのでメモ。

実施環境:
Linux
[testuser@testhost ~]$ uname -a
Linux testhost 4.18.0-147.8.1.el8_1.x86_64 #1 SMP Thu Apr 9 13:49:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
[testuser@testhost ~]$ echo $SHELL
/bin/bash

ファイルやディレクトリのパスから、ファイル名のみやディレクトリ名のみ、あるいは親ディレクトリのパスのみを切り出したい場合があります。
そのような時に使用するのが、basenameコマンドとdirnameコマンドです。

ファイル名、ディレクトリ名のみを切り出す場合はbasenameコマンドを使用します。
拡張子を同時に指定することで、ファイル名から拡張子を除外した文字列も取得可能です。
ルートディレクトリを指定した場合は、ルートディレクトリが表示されます。

Linux
[testuser@testhost ~]$ basename /var/log/boot.log
boot.log
[testuser@testhost ~]$ basename var/log/boot.log
boot.log
[testuser@testhost ~]$ basename boot.log
boot.log
[testuser@testhost ~]$ basename /var/log/boot.log .log
boot
[testuser@testhost ~]$ basename /var/log
log
[testuser@testhost ~]$ basename /var/log/
log
[testuser@testhost ~]$ basename /
/

親ディレクトリ部分を切り出す場合はdirnameコマンドを使用します。
こちらもルートディレクトリを指定した場合、ルートディレクトリが表示されます。
また、ファイル名、ディレクトリ名のみを指定した場合はカレントディレクトリを表す.が表示されます。

Linux
[testuser@testhost ~]$ dirname /var/log/boot.log
/var/log
[testuser@testhost ~]$ dirname var/log/boot.log
var/log
[testuser@testhost ~]$ dirname boot.log
.
[testuser@testhost ~]$ dirname /var/log
/var
[testuser@testhost ~]$ dirname /var/log/
/var
[testuser@testhost ~]$ dirname /var
/
[testuser@testhost ~]$ dirname /
/

無論、これらのコマンドを使用せず、/を区切り文字として地道に切り分けて取得することも可能です。

Linux
[testuser@testhost ~]$ echo "/var/log/boot.log" | awk -F/ '{print $NF}'
boot.log
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?