1

I have 2 files sorted by numerically. I need help with shell script to read these 2 files and do a 1:1 mapping and rename the filenames with the mapped case#;

For example:

cat case.txt
10_80
10_90

cat files.txt
A BCD_x 1.pdf
A BCD_x 2.pdf

ls pdf_dir
A BCD_x 1.pdf A BCD_x 2.pdf

Read these 2 txt and rename the pdf files in pdf_dir :

A BCD_x 1.pdf as A BCD_10_80.pdf
A BCD_x 1.pdf as A BCD_10_90.pdf
4

4 回答 4

2

使用paste创建“映射”,然后使用 shell 工具进行重命名。

shopt -s extglob
while IFS=$'\t' read file replacement; do
    echo mv "$file" "${file/x +([0-9])/$replacement}"
done < <(paste files.txt case.txt)

满意时删除“回声”。

于 2013-08-09T19:17:28.743 回答
1

使用普通数组和 sed 替换 - 在 mv 之前删除 echo 将为您提供移动功能。您可以更改 /path/to/pdf_dir/ 以指定所需目录的路径

#!/bin/bash
i=0
while read line
do
    arr[i]="$line"
  ((i=i+1));
done < files.txt

i=0
while read case
do
   newFile=$(echo "${arr[i]}" | sed "s/x/"$case"/")
   echo mv /path/to/pdf_dir/"${arr[i]}" /path/to/pdf_dir/"$newFile"
   ((i=i+1))
done < case.txt
于 2013-08-10T00:32:06.600 回答
1

使用 awk:

awk 'FNR==NR{a[FNR]=$0;next}
  {f=$0; sub(/_x /, "_" a[FNR] " "); system("mv \"" f "\" \"" $0 "\"")}' case.txt files.txt
于 2013-08-09T19:09:03.820 回答
0

如果您有 Bash 4.0,这可能会有所帮助:

#!/bin/bash

declare -A MAP
I=0
IFS=''

while read -r CASE; do
    (( ++I ))
    MAP["A BCD_x ${I}.pdf"]="A BCD_${CASE}.pdf"
done < case.txt

while read -r FILE; do
    __=${MAP[$FILE]}
    [[ -n $__ ]] && echo mv "$FILE" "$__"  ## Remove echo when things seem right already.
done < files.txt

注意:确保以 UNIX 文件格式运行脚本。

于 2013-08-09T19:07:44.733 回答