2013-04-11 91 views
0

我的文件夹和文件结构像重命名文件外壳


Folder/1/fileNameOne.ext 
Folder/2/fileNameTwo.ext 
Folder/3/fileNameThree.ext 
... 

我如何重命名文件,使得输出变为


Folder/1_fileNameOne.ext 
Folder/2_fileNameTwo.ext 
Folder/3_fileNameThree.ext 
... 

这又如何在Linux shell中实现吗?

+0

还问[askubuntu](http://askubuntu.com/q/280333/10127) – 2013-04-11 21:44:08

+0

我已经添加了解决方案[AskUbuntu](http://stackoverflow.com/a/15953333/1433665 ) – TheKojuEffect 2013-04-12 02:32:13

回答

0

AskUbuntu这个解决方案为我工作。

这里是一个bash脚本,它是:

注:此脚本不工作,如果任何文件名中包含空格。

 
#! /bin/bash 

# Only go through the directories in the current directory. 
for dir in $(find ./ -type d) 
do 
    # Remove the first two characters. 
    # Initially, $dir = "./directory_name". 
    # After this step, $dir = "directory_name". 
    dir="${dir:2}" 

    # Skip if $dir is empty. Only happens when $dir = "./" initially. 
    if [ ! $dir ] 
    then 
     continue 
    fi 

    # Go through all the files in the directory. 
    for file in $(ls -d $dir/*) 
    do 
     # Replace/with _ 
     # For example, if $file = "dir/filename", then $new_file = "dir_filename" 
     # where $dir = dir 
     new_file="${file/\//_}" 

     # Move the file. 
     mv $file $new_file 
    done 

    # Remove the directory. 
    rm -rf $dir 
done 
  • 复制 - 粘贴到文件中的脚本。
  • 使其可执行使用
 
chmod +x file_name 
  • 移动脚本到目标目录。在你的情况下,这应该在Folder/
  • 使用./file_name运行脚本。
1

如果名称是始终不变的,这可能工作,即“文件”:

for i in {1..3}; 
do 
    mv $i/file ${i}_file 
done 

如果你有一个数字范围更迪尔斯,为{x..y}改变{1..3}

我用${i}_file而不是$i_file,因为它会考虑$i_filei_file的变量,而我们只想i作为附加给它的变量,file和文字。

+0

姓名不同:-( – TheKojuEffect 2013-04-11 15:18:36

+0

更新你的问题! – fedorqui 2013-04-11 15:19:06

2

你想要做多少种不同的方式?

如果名称不包含空格或换行符或其他有问题的字符,并且中间目录始终为单个数字,并且如果在文件file.list中每个行只有一个名称的文件列表将被重命名,许多可能的方法可以做到重命名为:

sed 's%\(.*\)/\([0-9]\)/\(.*\)%mv \1/\2/\3 \1/\2_\3%' file.list | sh -x 

你会避免通过shell中运行的命令,直到你确定它会做你想要的东西;看看生成的脚本,直到它的权利。

还有一个叫rename的命令 - 不幸的是,有几个实现,并不都是同样强大的。如果你有基于Perl的(使用一个Perl的正则表达式旧名称映射到新名称)的一个你可以使用:

rename 's%/(\d)/%/${1}_%' $(< file.list) 
+0

我只是想问你出于好奇,如果任何'重命名'可以做到这一点(我从来没有使用它们),因为我确信你会知道的,你的编辑速度更快:-) – 2013-04-11 15:25:30

+0

+1。忍不住越来越多地每天都在学习。 'rename'是我不知道的命令,对于这些情况非常强大。 – fedorqui 2013-04-11 15:32:57

+1

我使用骆驼书第一版(Perl 4的原始编程Perl)的版本,尽管从那以后我已经稍微更新了它。请参阅源代码中的[如何使用前缀/后缀重命名](http://stackoverflow.com/questions/208181/how-to-rename-with-prefix-suffix/208389#208389)。 – 2013-04-11 15:33:27

2

使用循环如下:

while IFS= read -d $'\0' -r line 
do 
    mv "$line" "${line%/*}_${line##*/}" 
done < <(find Folder -type f -print0) 

该方法处理文件名和中间目录中的空格,换行符和其他特殊字符不一定必须是单个数字。

+0

+1:'bash'密集型,但有效。 – 2013-04-11 15:43:10