如何重命名zip存档中的文件而不提取和重新压缩它们?

Top*_*opo 5 linux bash

我需要在所有的压缩文件中的文件从命名AAAAA-filename.txtBBBBB-filename.txt了,我想知道如果我可以,而不必提取所有文件,重命名自动执行此任务,然后再压缩。一次解压缩一个,然后重命名并再次压缩是可以接受的。

我现在所拥有的是:

for file in *.zip
do
    unzip $file
    rename_txt_files.sh
    zip *.txt $file
done;
Run Code Online (Sandbox Code Playgroud)

但是我不知道是否有一个更好的版本,我不必使用所有额外的磁盘空间。

amd*_*xon 1

计划

  • 查找带有字符串的文件名的偏移量
  • 使用 dd 覆盖新名称(注意仅适用于相同的文件名长度)。否则还必须找到并覆盖 filenamelength 字段。

在尝试此操作之前备份您的 zip 文件

zip_重命名.sh

#!/bin/bash

strings -t d test.zip | \
grep '^\s\+[[:digit:]]\+\sAAAAA-\w\+\.txt' | \
sed 's/^\s\+\([[:digit:]]\+\)\s\(AAAAA\)\(-\w\+\.txt\).*$/\1 \2\3 BBBBB\3/g' | \
while read -a line; do
  line_nbr=${line[0]};
  fname=${line[1]};
  new_name=${line[2]};
  len=${#fname};
#  printf "line: "$line_nbr"\nfile: "$fname"\nnew_name: "$new_name"\nlen: "$len"\n";
  dd if=<(printf $new_name"\n") of=test.zip bs=1 seek=$line_nbr count=$len conv=notrunc  
done;
Run Code Online (Sandbox Code Playgroud)

输出

$ ls
AAAAA-apple.txt  AAAAA-orange.txt  zip_rename.sh
$ zip test.zip AAAAA-apple.txt AAAAA-orange.txt 
  adding: AAAAA-apple.txt (stored 0%)
  adding: AAAAA-orange.txt (stored 0%)
$ ls
AAAAA-apple.txt  AAAAA-orange.txt  test.zip  zip_rename.sh
$ ./zip_rename.sh 
15+0 records in
15+0 records out
15 bytes (15 B) copied, 0.000107971 s, 139 kB/s
16+0 records in
16+0 records out
16 bytes (16 B) copied, 0.000109581 s, 146 kB/s
15+0 records in
15+0 records out
15 bytes (15 B) copied, 0.000150529 s, 99.6 kB/s
16+0 records in
16+0 records out
16 bytes (16 B) copied, 0.000101685 s, 157 kB/s
$ unzip test.zip 
Archive:  test.zip
 extracting: BBBBB-apple.txt         
 extracting: BBBBB-orange.txt        
$ ls
AAAAA-apple.txt   BBBBB-apple.txt   test.zip
AAAAA-orange.txt  BBBBB-orange.txt  zip_rename.sh
$ diff -qs AAAAA-apple.txt BBBBB-apple.txt 
Files AAAAA-apple.txt and BBBBB-apple.txt are identical
$ diff -qs AAAAA-orange.txt BBBBB-orange.txt 
Files AAAAA-orange.txt and BBBBB-orange.txt are identical
Run Code Online (Sandbox Code Playgroud)