如何更改目录目录中的文件名?

时间:2016-10-04 00:13:49

标签: bash

我正在尝试编写一个将在目录中执行的bash脚本,并修改当前目录下的目录中的文件名。我达到了可以回显每个文件的当前路径名以及该文件的新路径名的程度。

我认为我所要做的就是将回声改为mv并让她撕裂。错误!显然bash不允许mv对路径名进行操作。

我很高兴有关如何从这里开始的任何建议。

1 个答案:

答案 0 :(得分:0)

我现在正在工作。我将尝试发布以下代码。非常感谢Charles Duffy和Greg的Wiki。

#!/bin/bash
# I listen to many audiobooks.  Sometimes the file names are
# such that they cannot be directly loaded into iTunes because 
# the files names contain the track number before the disk number
# so iTunes sorts all the track 01 and then all the track 02, etc rather 
# than all the tracks of disk 1 in order and then all the tracks of 
# disk 2 in order, etc.
#
# This script fixes this problem.  The files are in sub-directories of
# a master directory with one sub-directory for each disk and the
# format of the files names is:
#
# 01 Disc 01 We Were Soldiers Once ... and Young.mp3
#
# The first 2 chars are the track number and it needs to be moved
# somewhere after the disc number. This script moves it to just
# before the .mp3.

# You might have the same problem but a different format but you can
# change the script.  Greg's Wiki gives great Examples of Filename
# Manipulation.  Find it here: http://mywiki.wooledge.org/BashFAQ/073 
# 
#set -x
cd " Place full path name of the master directory here "
pwd
for dir in *
do
    echo $dir
    cd "${dir}"  # Move from Master Directory to a sub-directory
    pwd
#ls
    for nameext in *.mp3
    do
        echo $nameext
        name=${nameext%.*} # name has the .mp3 removed
        echo ${name}
        tracknum=${name:0:2} # tracknum is the 1st 2 chars
        echo ${tracknum}
        name=${name:3}  # Remove tracknum from front of name
        echo ${name}
        name=${name}" "${tracknum} # Add tracknum to end of name
        echo ${name}
        newnameext=${name}.mp3 # Add .mp3 back onto name
        echo ${newnameext}
        echo ${nameext}-${newnameext}
        mv "${nameext}" "${newnameext}"
        echo


    done

    cd ..  # Move back to Master Directory
done
exit
done