やりたいこと
出力ファイルの名前をつけるときに、実行しているスクリプト名や引数に取っているファイル名をいじったものをつけたい。
ただ、パスは長くなるのでいらない。拡張子も同様
でも毎回手で入力するとしんどい
環境
レッドハットエンタープライズの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の結果を変数に渡す
どの程度まで変数を代入できるのかが全くわからない。
このぐらいまで分解しないと実行できなかった。また調べる。
li_asm=("0" "3" "5" "10" "20" )
li_min_ol=("0" "1000" "2000" "5000" "10000" )
seq_path=("${read_1}" "${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}"
ちゃんと演算子を入れることはできる。