LoginSignup
0
0

More than 3 years have passed since last update.

basename :実行ファイルのファイル名を変数に代入する[備忘録]

Last updated at Posted at 2019-07-31

やりたいこと

出力ファイルの名前をつけるときに、実行しているスクリプト名や引数に取っているファイル名をいじったものをつけたい。
ただ、パスは長くなるのでいらない。拡張子も同様

 でも毎回手で入力するとしんどい

環境

レッドハットエンタープライズのCentOS 7です。

bash-4.2$ uname -r
3.10.0-957.5.1.el7.x86_64
bash-4.2$ cat /etc/redhat-release 
CentOS Linux release 7.6.1810 (Core) 

basename

ファイル名からディレクトリと接尾辞を取り除いてくれるすごいコマンド

とりあえずman コマンドで使い方を。

basename, dirname -- return filename or directory portion of pathname

気が利きますね。という感じ

SYNOPSIS
basename string [suffix]
basename [-a] [-s suffix] string [...]
dirname string

dirname でdirが取れるのは初めて知った。

これだけでは、どんなコマンドかわからないので、説明をみると、

The basename utility deletes any prefix ending with the last slash `/'
character present in string (after first stripping trailing slashes), and
a suffix, if given. The suffix is not stripped if it is identical to the
remaining characters in string. The resulting filename is written to the
standard output. A non-existent suffix is ignored. If -a is specified,
then every argument is treated as a string as if basename were invoked
with just one argument. If -s is specified, then the suffix is taken as
its argument, and all other arguments are treated as a string.

とあるので、最後の/まで切ってくれる上に、suffix(接尾辞)を指定してあげると(最後につくなら拡張子でなくても)消去してくれるみたい。
 ただし、接尾辞が文字中に複数ある場合は消去しないみたい。

コマンド

例1 shellスクリプトのファイル名をprefixにしたいとき

prefix=`basename $0 .sh`

例2 PATH aにあるtxt fileをprefixにする

prefix=`basename PATH/TO/TXT/FILE/~.txt .txt`

で〜がprefixに入る。

例3 複数のパスを繋げる

 basename -a オプション,出力をデフォルトの改行ではなくnullにする^z オプションを使う
 例えば、スクリプト名と引数1の名前を繋げたい時には、

`prefix -a -z $0 $1`

-z オプションがあるかは環境によりそうです。(ちなみに僕のMac 10.14 にはなかった。)
また、-a optionをつけるとsuffixはつけれなさそう。。(多分方法はあるんだろうけど不明)

例4 basenameの結果を変数に渡す

どの程度まで変数を代入できるのかが全くわからない。
このぐらいまで分解しないと実行できなかった。また調べる。

test.sh
li_asm=("0" "3" "5" "10" "20" )
li_min_ol=("0" "1000" "2000" "5000" "10000" )
seq_path=("${read_}" "${read_2}")

a=$((SGE_TASK_ID%5))
b=$((SGE_TASK_ID/5%5))
c=$((SGE_TASK_ID%2))

asm=${li_asm[a]}
min_ol=${li_min_ol[b]}
seq=${seq_path[c]}
echo " seq = ${seq}"

prefix="$(basename ${seq} .fq)_${asm}_${min_ol}"  
out_dir="${work_dir}/flye/${prefix}"

ちゃんと演算子を入れることはできる。

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