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

ファイル名をまとめて変更する

Posted at

背景・目的

  • ファイル名の不要部分を削除したかった
  • 一つずつやると間違えそうだったのでまとめてやりたかった
  • renameコマンドが使えなかった
  • BeforeをAfterにしたかった
# Before
20241014_hoge1.csv
20241014_hoge2.csv
20241014_hoge3.csv
20241014_hoge4.csv
20241014_hoge5.csv

# After
hoge1.csv
hoge2.csv
hoge3.csv
hoge4.csv
hoge5.csv

コマンド

$ find . -type f -name '*hoge*.csv' | sed 'p;s/20241014_//' | xargs -n 2 mv

ワンポイント解説

  • sed 'p'で変更前のファイル名を出力
  • 's//'でファイル名を変更して出力
  • <置換前> <置換後>の順番で出力することで、後続のxargsが処理しやすいようにしている

※ファイル名に空白が入っている場合は想定通りに動作しないのでrenameコマンドか他のやり方で行うこと

補足

renameコマンドが使えるなら以下の方がシンプル。
環境によってコマンドが古いので使い分けること。

# Perl版
$ rename '20241014_' '' *hoge*.csv
or
$ find . -type f -name '*hoge*.csv' -exec rename '20241014_' '' {} +

# util-linux版
$ rename 's/20241014_//' *hoge*.csv
or
$ find . -type f -name '*hoge*.csv' -exec rename 's/20241014_//' {} +
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?