【问题标题】:Renaming Multiples Files with Different Names in a Directory using shell使用 shell 重命名目录中具有不同名称的多个文件
【发布时间】:2012-12-11 23:26:38
【问题描述】:

我发现大多数此类问题的名称更改对于该目录中的整个文件集都是相同的。 但是我在这里遇到了一种情况,即为该目录中的每个文件赋予不同的名称,或者只是添加不同的前缀。

例如,我在一个目录中有大约 200 个文件,所有文件的文件名中都有数字。我想要做的是为每个文件添加 1 到 200 的前缀。比如1_xxxxxxxx.png,2_xxxxxxxx.png............200_xxxxxxxx.png

我正在尝试这个,但它不会每次都增加我的 $i,而是给每个文件一个前缀 1_。

echo "renaming files" 
i=1                                             #initializing
j=ls -1 | wc -l                                 #Count number of files in that dir
while [ "$i" -lt "$j" ]                         #looping 
do
    for FILE in * ; do NEWFILE=`echo $i_$FILE`; #swapping the file with variable $i
    mv $FILE $NEWFILE                           #doing the actual rename
    i=`expr $i+1`                               #increment $i
done

感谢您的任何建议/帮助。

【问题讨论】:

    标签: shell rename file-rename


    【解决方案1】:

    要使用expr 递增,您肯定需要空格(expr $i + 1),但您最好这样做:

    echo "renaming files" 
    i=1
    for FILE in * ; do
        mv $FILE $((i++))_$FILE
    done
    

    【讨论】:

      【解决方案2】:
      i=1
      for f in *; do
        mv -- "$f" "${i}_$f"
        i=$(($i + 1))
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-22
        • 2022-06-14
        • 2019-11-13
        • 2021-03-28
        • 1970-01-01
        • 2017-06-23
        • 2016-07-15
        • 2018-10-09
        相关资源
        最近更新 更多