テキストファイルを使用してファイルとフォルダの名前を変更する

テキストファイルを使用してファイルとフォルダの名前を変更する

スペースで区切られたテキストファイルを使用して、ファイルとディレクトリの名前を変更しようとしています。

これファイル.txt次のようになります。

dir1-1 dir1_1
dir2-1 dir223_1

私のコマンドは次のとおりです。

xargs -r -a **files.txt** -L1 mv

ファイルは次のとおりです(ディレクトリ1)。

dir1-1.txt dir1-1.gzip dir1-1-something.text

ファイルの出力は次のようになります(dir1-1)。

dir1_1.txt dir1_1.gzip dir1_1-something.text

ディレクトリ(dir2)のファイルは次のとおりです。

dir2-1.py dir2-1.txt dir2-1.text

出力は次のようになります。

dir223_1.py dir223_1.txt dir223_1.text

このコマンドは、フォルダ名をdir1-1からdir1_1、dir2-1からdir223_1soにのみ変更できますが、サブディレクトリのファイル名は変更しません。そのディレクトリのファイルにも、これらのディレクトリの接頭辞があります。 (例:dir1-1.txt dir1-1.gzip dir1-1.csv)

それは次のとおりです。 代替ファイル名を含むテキストファイルを使用してファイル名を変更するスクリプト

あなたの助けを楽しみにしています。

ベストアンサー1

これを行うにはいくつかの方法がありますが、以下は1つのアプローチを説明する非常に簡単で簡単な例です。

$ cat files.txt 
dir1-1 dir1_1
dir2-1 dir223_1

$ cat rename.sh
#!/bin/bash

# make some dirs and files to test with:
d='dir1-1'; mkdir "$d"; for ext in .txt .gzip -something.txt; do touch "$d/$d$ext" ; done
d='dir2-1'; mkdir "$d"; for ext in .py .txt .text; do touch "$d/$d$ext" ; done

# now rename them:
while read -r old new ; do
  # rename the directory too
  mv -v "$old" "$new"

  # and rename the files
  if [ -d "$new" ] ; then
    for f in "$new/"* ; do
      mv -v "$f" "$(printf "%s" "$f" | sed -e "s/$old/$new/g")"
    done
  fi
  echo
done < files.txt

$ chmod +x rename.sh

$ ./rename.sh 
renamed 'dir1-1' -> 'dir1_1'
renamed 'dir1_1/dir1-1.gzip' -> 'dir1_1/dir1_1.gzip'
renamed 'dir1_1/dir1-1-something.txt' -> 'dir1_1/dir1_1-something.txt'
renamed 'dir1_1/dir1-1.txt' -> 'dir1_1/dir1_1.txt'

renamed 'dir2-1' -> 'dir223_1'
renamed 'dir223_1/dir2-1.py' -> 'dir223_1/dir223_1.py'
renamed 'dir223_1/dir2-1.text' -> 'dir223_1/dir223_1.text'
renamed 'dir223_1/dir2-1.txt' -> 'dir223_1/dir223_1.txt'

注:files.txtファイル名とディレクトリ名には、古いパターンと新しいパターンを区別するスペースがあり、デフォルトのreadIFS設定$' \t\n'(スペース、タブ、または改行)を使用しているため、次のスクリプトは次のスクリプトを含まないすべてのファイル名パターンに対して機能します。します。これらの文字 (または/で区切り文字として使用されるので a sed)。

おすすめ記事