使用文本文件作为源重命名文件

时间:2017-07-07 17:44:03

标签: bash file-rename batch-rename

在一个文件夹中,我有600个文件,编号从001到600.它看起来像foo_001.bar。在文本文件中,我是数字&这个文件夹的标题。现在我想用文本文件中的相应001标题foobar重命名foo_001.bar。

但我不知道如何在Linux Mint上正确地做到这一点。有人可以帮我或给我一个提示吗?

titles.txt的内容如下所示。使用数字和标题之间的标签(可以轻易地改变)。

001 title of 1
002 this is 2
003 and here goes 3
004 number four
005 hi this is five
etc

文件夹的内容如下所示。没有例外。

file_001.ext
file_002.ext
file_003.ext
file_004.ext
file_005.ext
etc

1 个答案:

答案 0 :(得分:3)

使用read循环浏览您的文件,使用 awk cut获取分隔的列(谢谢您,@ Jack)和mv相应的文件。在这个非常简单的实现中,我假设包含新名称的文本文件位于./filenames,并且从包含文件的目录中调用脚本。

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
        NR=$(echo "$line" | cut -f 1)
        NAME=$(echo "$line" | cut -f 2)
        if [ -f "foo_${NR}.ext" ] ; then
                mv "foo_${NR}.ext" "$NAME"
        fi
done < filenames
相关问题