Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename files in zip archive without extracting and recompressing them?

Tags:

linux

bash

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.

What I have now is:

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.

like image 678
Topo Avatar asked Sep 28 '15 18:09

Topo


1 Answers

plan

  • 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..

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;

output

$ 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
like image 183
amdixon Avatar answered Oct 14 '22 14:10

amdixon