linux - 如何在不解压缩和重新压缩的情况下重命名 zip 存档中的文件?

标签 linux bash

我需要将 zip 文件中的所有文件从 AAAAA-filename.txt 重命名为 BBBBB-filename.txt,我想知道我是否可以自动化此任务无需提取所有文件、重命名然后再次压缩。一次解压一个,重命名并再次压缩是可以接受的。

我现在拥有的是:

for file in *.zip
do
    unzip $file
    rename_txt_files.sh
    zip *.txt $file
done;

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

最佳答案

计划

  • find offsets of filenames with strings
  • use dd to overwrite new names ( note will only work with same filename lengths ). otherwise would also have to find and overwrite the filenamelength field..

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

zip_rename.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;

输出

$ 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

关于linux - 如何在不解压缩和重新压缩的情况下重命名 zip 存档中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32829839/

相关文章:

c++ - MinGW 下 windows 中的 Protobuf

bash - docker '$ yes | true' 中的 Gitlab runner 以 exit 1 返回

linux - 如何使用cli53向路由53添加srv记录

c - 32 位应用程序如何在 64 位 Linux 上进行系统调用?

linux - 为什么 "read"不读取命令输出的第一行?

BASH 命名管道锁定

linux - 通过我的应用程序连接到 SFTP

linux - Ubuntu Docker 容器立即停止,Dockerfile 出现问题?

arrays - PHPStorm 提示数组变量的简单使用

bash - 如何在每次提交时运行脚本