3
1

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.

シェルスクリプトでディレクトリ名・ファイル名とファイル内に含まれる文字列を一括置換する方法

3
Posted at

はじめに

この記事は以下のことを実行するシェルスクリプトについて記載したものです
・ディレクトリ名やファイル名に含まれる特定の文字列を一括で置換する
・ファイル内の特定の文字列を一括で置換する

環境
mac OS 10.14.6

シェルスクリプトの内容

# 置換前と置換後の文字列を対話モードで受け付ける
echo "Input old text"
read oldText
echo "Input new text"
read newText


# フォルダ名、ファイル名を置換する
for i in $(seq $(find . -type d | wc -l))
do
    find . -maxdepth $i -name '*'$oldText'*' | \
    while read line
    do newline=$(echo $line | sed 's/'$oldText'/'$newText'/g')
        echo $newline
        mv "$line" $newline
    done
done

# ファイル内に含まれる文字列を置換する
find ./ -name '*.js' -exec sed -i '' 's/'$oldText'/'$newText'/g' {} \;

参考にしたサイト

再帰的にファイル名やディレクトリ名にある半角スペースをアンダースコア ( _ )で置き換えるスクリプト: Linux & Mac 対応
https://www.nemotos.net/?p=1919
コマンドごとに丁寧な説明が書かれていたのでとても参考になりました。ありがとうございます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?