如何使用与引用相同的大小写重命名文件和文件夹

时间:2016-09-09 21:07:32

标签: linux bash

我必须递归重命名一个完整的文件夹树('target'),以便它具有 文件服务器('server')上的文件和文件夹名称相同。

实施例。在'target'

./target 
./target/FILE 
./target/dir2 
./target/dir2/File2 
./target/DIR1 
./target/DIR1/file1 

'server'

./target 
./target/file 
./target/DIR2 
./target/DIR2/File2 
./target/dir1 
./target/dir1/File1 

我很确定如果文件名相同(以小写字母比较) 文件是相同的(也许我可以添加校验和比较)。 最终结果应该是'target'与'server'具有相同的文件名。
我尝试过bash(应该是最好的解决方案)......但是bash恨我!任何线索? TY!

2 个答案:

答案 0 :(得分:0)

首先,创建包含问题中打印的目录的2个文件source.txttarget.txt

你可以这样做:

(cd path/to/the/server;find . -type d) > target.txt
(cd path/to/the/source;find . -type d) > source.txt

然后运行这个shell:

while read target_dir
do
    fixed_name=$(grep -i ^$target_dir\$ source.txt)
    if [ ! -z "$fixed_name" ] ; then
      (cd path/to/the/server;mv $target_dir $fixed_name)
    fi
done < target.txt

基本上,对于target.txt文件的每一行,它在source.txt文件中查找正确对应的对应项。如果找到,则发出位于path/to/the/server目录中的rename命令。

答案 1 :(得分:0)

谢谢Jean:你指导我解决方案!它有点复杂:
and then set the length of the array to one minus the index of '

#!/bin/bash
# 160912
# match filenames char-cases on target path as in server path
# usage : $0 targetDir serverDir

TARGET_PATH=$1

MAKE_EQUAL()
{
  while read server_name
  do
      new_target_name=$(grep -i ^$server_name\$ targetList.txt)
      if [ ! -z "$new_target_name" ] && [ "$server_name" != "$new_target_name" ] ; then
        echo "  $new_target_name --> $server_name"
        (cd $TARGET_PATH;mv $new_target_name $server_name)
      fi
  done < serverList.txt
}

if [ ! -d "$1" -o ! -d "$2" ] ; then
    echo "Paths not found!"
    exit 0
fi

# Change directories changing depth level until is the last directory level
DIRLEVEL=1 
LASTLEVEL=0
(cd $2;find . -maxdepth $DIRLEVEL -type d) > serverList.txt
while [ "$LASTLEVEL" == "0" ]
  do
    echo "Match directory level $DIRLEVEL:"
    (cd $1;find . -maxdepth $DIRLEVEL -type d) > targetList.txt
    MAKE_EQUAL
    DIRLEVEL=`expr $DIRLEVEL + 1` 
    (cd $2;find . -maxdepth $DIRLEVEL -type d) > nextServerList.txt
    diff nextServerList.txt serverList.txt > /dev/null
    if [ $? -eq 0 ] ; then
      LASTLEVEL=1
    else
      mv nextServerList.txt serverList.txt
    fi
  done

echo "Match files:"

(cd $1;find . -type f) > targetList.txt
(cd $2;find . -type f) > serverList.txt
MAKE_EQUAL

echo "Done!"