Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 通过从文件中提取新名称来重命名文件_Bash_Rename_Command Line Interface - Fatal编程技术网

Bash 通过从文件中提取新名称来重命名文件

Bash 通过从文件中提取新名称来重命名文件,bash,rename,command-line-interface,Bash,Rename,Command Line Interface,我有一堆需要重命名的文件,新的名称在一个文本文件中 示例文件名: ASBC_Fishbone_Ia.pdf Ia. Propagation—Design Considerations.pdf 文本文件中的示例条目: Ia. Propagation—Design Considerations 预期的新文件名: ASBC_Fishbone_Ia.pdf Ia. Propagation—Design Considerations.pdf 或 使用典型的linux cli工具进行此操作的好方法

我有一堆需要重命名的文件,新的名称在一个文本文件中

示例文件名:

ASBC_Fishbone_Ia.pdf
Ia. Propagation—Design Considerations.pdf
文本文件中的示例条目:

Ia. Propagation—Design Considerations
预期的新文件名:

ASBC_Fishbone_Ia.pdf
Ia. Propagation—Design Considerations.pdf

使用典型的linux cli工具进行此操作的好方法是什么?我在考虑ls、grep和rename的组合?

您可以尝试:

#!/bin/bash

# Do not allow the script to run if it's not Bash or Bash version is < 4.0 .
[ -n "$BASH_VERSION" ] && [[ BASH_VERSINFO -ge 4 ]] || exit 1

# Do not allow presenting glob pattern if no match is found.
shopt -s nullglob

# Use an associative array.
declare -A MAP=() || exit 1

while IFS=$'\t' read -r CODE NAME; do
    # Maps name with code e.g. MAP['Ia']='Propagation—Design Considerations'
    MAP[${CODE%.}]=$NAME
done < /path/to/text_file

# Change directory. Not needed if files are in current directory.
cd "/path/to/dir/containing/files" || exit 1

for FILE in *_*.pdf; do
    # Get code from filename.
    CODE=${FILE##*_} CODE=${CODE%.pdf}

    # Skip if no code was extracted from file.
    [[ -n $CODE ]] || continue

    # Get name from map based from code.
    NAME=${MAP[$CODE]}

    # Skip if no new name was registered based on code.
    [[ -n $NAME ]] || continue

    # Generate new name.
    NEW_NAME="${CODE}. $NAME.pdf"

    # Replace spaces with _ at your preference. Uncomment if wanted.
    # NEW_NAME=${NEWNAME// /_}

    # Rename file. Remove echo if you find it correct already.
    echo mv -- "$FILE" "$NEW_NAME"
done
#/bin/bash
#如果脚本不是Bash或Bash版本<4.0,则不允许运行该脚本。
[-n“$BASH_VERSION”]&&&[BASH_VERSINFO-ge 4]||退出1
#如果未找到匹配项,则不允许显示全局模式。
shopt-s nullglob
#使用关联数组。
声明-A映射=()| |退出1
而IFS=$'\t'读取-r代码名;做
#带有代码的映射名称,例如映射['Ia']=“传播-设计注意事项”
映射[${CODE%.}]=$NAME
完成
您如何知道文件中的哪个名称与磁盘上的哪个文件匹配?它们都是pdf文件吗?然后您可以像这样使用pdf元数据:pdfinfo file.pdf | grep Title | sed's/Title:[]*/'