如何在OSX中批量重新排列文件名?

时间:2022-08-05 10:39:10

I am running OSX Yosemite.

我正在运行OSX Yosemite。

I have a batch of files named in this format: XX-YYYab.txt

我有一批以这种格式命名的文件:XX-YYYab.txt

The XX are variable numbers, as are the YYY. The 'a' and 'b' are variable letters.

XX是可变数字,YYY也是如此。 'a'和'b'是可变字母。

I would like to rearrange the file name to get YYY-XXab.txt so that I can sort by the YYY component.

我想重新排列文件名以获取YYY-XXab.txt,以便我可以按YYY组件排序。

1 个解决方案

#1


I would do it like this in the Terminal - run it on a COPY of your files first in case it clobbers something. Make sure to change directory to where your files are before you run it.

我会在终端中这样做 - 首先在你的文件的COPY上运行它,以防它破坏某些东西。确保在运行文件之前将目录更改为文件所在的位置。

Save the following file as renamethem

将以下文件另存为renamethem

#!/bin/bash
# Loop through all files that start with digits, have dashes, and end in ".txt"
for f in [0-9]*-*.txt;do 

    # Get xx - the leading digits before a dash
    xx=${f/-*/}

    # Get yy - the digits after the dash
    yy=$(sed -E 's/.*-([0-9]*).*/\1/' <<< $f)

    # Get the letters before ".txt"
    zz=$(sed -E 's/.*[0-9](.*)\.txt/\1/' <<< $f)

    # DEBUG echo $xx, $yy, $zz

    # Remove the word "echo" below to do the actual rename
    echo mv "$f" "${yy}-${xx}${zz}.txt"
done

Then do the following just once to make it executable

然后执行以下操作以使其可执行

chmod +x renamethem

Then run it by typing

然后键入来运行它

/.renamethem

Sample Output

mv 12-345ab.txt 345-12ab.txt
mv 333333-9999axrt.txt 9999-333333axrt.txt
mv 45-3rm.txt 3-45rm.txt

#1


I would do it like this in the Terminal - run it on a COPY of your files first in case it clobbers something. Make sure to change directory to where your files are before you run it.

我会在终端中这样做 - 首先在你的文件的COPY上运行它,以防它破坏某些东西。确保在运行文件之前将目录更改为文件所在的位置。

Save the following file as renamethem

将以下文件另存为renamethem

#!/bin/bash
# Loop through all files that start with digits, have dashes, and end in ".txt"
for f in [0-9]*-*.txt;do 

    # Get xx - the leading digits before a dash
    xx=${f/-*/}

    # Get yy - the digits after the dash
    yy=$(sed -E 's/.*-([0-9]*).*/\1/' <<< $f)

    # Get the letters before ".txt"
    zz=$(sed -E 's/.*[0-9](.*)\.txt/\1/' <<< $f)

    # DEBUG echo $xx, $yy, $zz

    # Remove the word "echo" below to do the actual rename
    echo mv "$f" "${yy}-${xx}${zz}.txt"
done

Then do the following just once to make it executable

然后执行以下操作以使其可执行

chmod +x renamethem

Then run it by typing

然后键入来运行它

/.renamethem

Sample Output

mv 12-345ab.txt 345-12ab.txt
mv 333333-9999axrt.txt 9999-333333axrt.txt
mv 45-3rm.txt 3-45rm.txt