1
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 1 year has passed since last update.

【ShellScript】ファイル名をリネームする

1
Posted at

はじめに

こんにちは!
今回はShellScriptでちょっとしたツールを作成したので、コピペで使えるコードについて書いていきたいと思います(ほんの一部修正する必要はありますが。。)。

作成したツール

作成したツールとしては、特定の文字列を削除してリネームするプログラムです。
例としては test_picture_1.png というファイルがあったとして test_ を削除したいなという時にプログラムを実行すると picture_1.png にリネームしてくれるというツールになります。
使い方としてはshを実行して対象のファイル名をターミナルに入力するだけ(下記で言うと「対象ファイル」の部分を入力する必要がある)であとは特に何もしないでリネームしてくれます。ただshファイルを置く場所には注意してください!

実行結果
# Before (実行前)
dir 
 ┗ 対象ファイル
            ┗ test
         ┗ test_picture_1.png
         ┗ test_picture_2.png
         ┗ test_picture_3.png
         ┗ test_picture_4.png
         ┗ test_picture_5.txt

 ┗ test.sh(今回作成ファイル)

# After(実行後)
dir 
 ┗ 対象ファイル
            ┗ test
         ┗ picture_1.png
         ┗ picture_2.png
         ┗ picture_3.png
         ┗ picture_4.png
         ┗ test_picture_5.txt

 ┗ test.sh(今回作成ファイル)

実際のコード

ということで以下がコードになります。
コメント部分に記載していますが、一部修正していただく必要があります。

shellScript
# プロンプトをechoを使って表示
echo フォルダ名を入力してください!!
# 入力を受付、その入力を「dir_name」に代入
read dir_name 
# 結果を表示
echo file name : $dir_name

# ファイルパスの取得
# testを入力していますが左記の場所を修正する必要がある path="./$dir_name/ここを修正する/*"
path="./$dir_name/test/*"
echo $path
# 今回はpngを指定していますが対象ファイルに合わせて修正してください .txt とか 
files=`find $path -maxdepth 0 -type f -name *.png`
echo start rename
for file in $files;
do
    # ファイル名のみに変換する
    before_pngfile="${file##*/}"
    echo before file name : $file
    # rename後のパスに変換する
    # 削除したい文字列の変更をしてください左記部分 after_pngfile=./$dir_name/test/${before_pngfile/ここの部分を削除したい文字列にする必要があります/""}
    after_pngfile=./$dir_name/test/${before_pngfile/test_/""}
    echo after file name : $after_pngfile
    # ファイル名を置換する
    mv ${file} ${after_pngfile}
done
echo file rename success!

最後に

これを元々作成した理由としてがファイル名を部分削除する必要がある作業がありすごーーくめんどくさくて時間をかけたくなかったために作成しました。ただ個人的に使っているだけのため若干手抜き感はあるかもしれないですが、まぁそう思ったら自分なりの改良をしてみるのもいいのかなと思います。
最後までご覧いただきありがとうございました!

1
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
1
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?