0
3

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

【LINUX】複数ファイルの移動・リネーム(xargs mv)

Posted at

Linuxで同じディレクトリーである複数ファイルを別のフォルダーに移動し、リネームする方法を紹介します。
処理を纏めてシェルに書いてから、シェル実行するという形にします。

Shell実施前:ディレクトリー参照

[root@localhost ~]#
[root@localhost ~]#ls /var/www/html/dir1
file1.txt file2.txt sample.txt
[root@localhost ~]#ls /var/www/html/dir2
[root@localhost ~]#

Shell実施

 shellファイル

rmFiles.sh
# パス定義
## 移動元パス
dir1=/var/www/html/dir1
## 移動先パス
dir2=/var/www/html/dir2


# ログ出力
## ログファイル
logfile=/var/www/html/log/`date '+%Y%m%d'`'.log'


# メイン
exitcode=0
filecount=`find $dir1 -type f | wc -l`
if [[ $filecount -ne 0 ]]; then
      ls $dir1 | grep -v total | xargs -i mv -f $dir1/{} $dir2/{}.`date -d yesterday '+%Y%m%d%H%M%S'`
      if [[ ${?} -ne 0 ]]; then
            echo `date` " [ERROR] ファイル移動に失敗しました。" | tee -a $logfile
            exitcode=1
      fi
      echo `date` " [SUCCESS] ファイル移動に正常終了しました。" | tee -a $logfile
fi

exit ${exitcode}

 shellファイル起動

[root@localhost ~]#
[root@localhost ~]#./var/www/html/rmFiles.sh
user : root
2018年 5月 9日 水曜日 10:01:01 JST  [SUCCESS] ファイル移動に正常終了しました。
[root@localhost ~]#

Shell実施後:ディレクトリー参照

[root@localhost ~]#
[root@localhost ~]#ls /var/www/html/dir1
[root@localhost ~]#ls /var/www/html/dir2
file1.txt.20180509100101 file2.txt.20180509100101 sample.txt.20180509100101
[root@localhost ~]#
[root@localhost ~]#cat /var/www/html/log/20180509.log
2018年 5月 9日 水曜日 10:01:01 JST  [SUCCESS] ファイル移動に正常終了しました。
[root@localhost ~]#
0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?