created: 2019-07-16T02:23:13.000Z

bashでファイルの拡張子を一括変更する

たとえばsrc配下のjsファイルをぜんぶtsファイルに変更したい場合は以下のように書ける

$ find ./src -name '*.js' -type f \
  | perl -wnlE '/(\S+).js/ and say "$1.js $1.ts"' \
  | xargs -n2 mv

動作

  • find ./src -name '*.js' -type f
    • **/*.js なファイルパスを集めてきている
    • eg: ./src/app/pages/index.js
  • perl -wnlE '/(\S+).js/ and say "$1.js $1.ts"'
    • 受け取ったファイルパスからjsをとってtsをつけて出力
    • eg: ./src/app/pages/index.js ./src/app/pages/index.ts
  • xargs -n2 mv
    • mv にふたつのファイル名を渡してリネーム

xargs -n2 は以下のように書いてある

-n number
        Set the maximum number of arguments taken from standard input for each invocation of utility.  An invocation of utility will use less than number standard input arguments if
        the number of bytes accumulated (see the -s option) exceeds the specified size or there are fewer than number arguments remaining for the last invocation of utility.  The
        current default value for number is 5000.

-n2で2個づつ処理してくれるようになる

Set the maximum number of arguments

参考

その他

Linuxだとrenameコマンドというのがあって便利なようだ

perlスクリプトで、File::Rename::rename を呼んでいるだけだった (移植できないもんなのかな)

cat /usr/bin/rename

作者はLarry Wall

=head1 AUTHOR

Larry Wall
基礎からの新しいストレージ入門 基本技術から設計・運用管理の実践まで
[ad] 基礎からの新しいストレージ入門 基本技術から設計・運用管理の実践まで
坂下 幸徳 (単行本)