如何在不提取和重新压缩的情况下重命名zip存档中的文件? [英] How to rename files in zip archive without extracting and recompressing them?

查看:92
本文介绍了如何在不提取和重新压缩的情况下重命名zip存档中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to rename all the files on a zip file from AAAAA-filename.txt to BBBBB-filename.txt, and I want to know if I can automate this task without having to extract all files, rename and then zip again. Unzipping one at a time, renaming and zipping again is acceptable.

我现在拥有的是:

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

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

But I don't know if there is a fancier version of this where I don't have to use all that extra disk space.

推荐答案

计划

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

在尝试此操作之前备份您的zipfile

backup your zipfile before trying this

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

这篇关于如何在不提取和重新压缩的情况下重命名zip存档中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆