LoginSignup
2
1

More than 3 years have passed since last update.

シェルメモ-複数ファイルリネーム

Last updated at Posted at 2019-05-27

目標

ディレクトリ直下の指定ファイルを一気にリネームする
1. 複数ファイル名の同じキーワードを置き換える
2. 全てファイル(ディレクトリを含め)名の前にプレフィックス追加
3. 指定拡張子ファイルのみのファイル名前にプレフィックス追加

環境

Amazon Linux

# bash --version
bash --version
GNU bash, version 4.2.46(2)-release (x86_64-koji-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"

コード

1. 複数ファイル名の同じキーワードを置き換える

# ll
total 0
-rw-r--r-- 1 root root 0 May 28 15:57 stg_foo.txt
-rw-r--r-- 1 root root 0 May 28 15:57 stg_hoge.txt
# rename stg prd *.txt
# ll
total 0
-rw-r--r-- 1 root root 0 May 28 15:57 prd_foo.txt
-rw-r--r-- 1 root root 0 May 28 15:57 prd_hoge.txt

2. 全てファイル(ディレクトリを含め)名の前にプレフィックス追加

# ll
total 0
drwxr-xr-x 2 root root 6 May 28 16:06 testdir
-rw-r--r-- 1 root root 0 May 28 16:06 abc.tf
-rw-r--r-- 1 root root 0 May 28 16:07 efg.tf
-rw-r--r-- 1 root root 0 May 28 15:57 foo.txt
-rw-r--r-- 1 root root 0 May 28 15:57 hoge.txt
# for a in * ; do mv -i "${a}" "prefix_${a}"; done
# ll
total 0
drwxr-xr-x 2 root root 6 May 28 16:06 prefix_testdir
-rw-r--r-- 1 root root 0 May 28 16:06 prefix_abc.tf
-rw-r--r-- 1 root root 0 May 28 16:07 prefix_efg.tf
-rw-r--r-- 1 root root 0 May 28 15:57 prefix_foo.txt
-rw-r--r-- 1 root root 0 May 28 15:57 prefix_hoge.txt

3. 指定拡張子ファイルのみのファイル名前にプレフィックス追加

# ll
total 0
drwxr-xr-x 2 root root 6 May 28 16:06 testdir
-rw-r--r-- 1 root root 0 May 28 16:06 abc.tf
-rw-r--r-- 1 root root 0 May 28 16:07 efg.tf
-rw-r--r-- 1 root root 0 May 28 15:57 foo.txt
-rw-r--r-- 1 root root 0 May 28 15:57 hoge.txt
# for a in `ls -l *.tf` ; do [ -f "${a}" ] && mv -i "${a}" "prefix_${a}"; done
# ll
total 0
drwxr-xr-x 2 root root 6 May 28 16:06 testdir
-rw-r--r-- 1 root root 0 May 28 15:57 foo.txt
-rw-r--r-- 1 root root 0 May 28 15:57 hoge.txt
-rw-r--r-- 1 root root 0 May 28 16:06 prefix_abc.tf
-rw-r--r-- 1 root root 0 May 28 16:07 prefix_efg.tf

2
1
1

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
1