When working with ZIP archives in Linux, you might encounter situations where you need to store a file under a different name than its original filename. The standard zip
command doesn't provide an obvious way to do this without first renaming the file on disk.
The most effective method is to use stdin redirection with the -
(hyphen) filename convention:
cat file.txt | zip -mqj archive.zip - -T file2.txt
Here's what each part does:
cat file.txt
- Reads the original file|
- Pipes the output to the next commandzip -mqj archive.zip -
- Creates a ZIP archive with stdin input-T file2.txt
- Specifies the target filename in the archive
If you prefer not to use pipes, you can create a temporary symbolic link:
ln -s file.txt file2.txt
zip -mqj archive.zip file2.txt
rm file2.txt
For multiple files with different target names, you can combine techniques:
cat file1.txt | zip -mqj archive.zip - -T doc1.txt
cat file2.txt | zip -mqj archive.zip - -T doc2.txt
To verify the contents were stored correctly:
unzip -l archive.zip
This should show your files with their new names in the archive.
- The
-T
option must come after the-
(stdin) specification - This method works with both the
zip
andunzip
utilities - For large files, the stdin method is more efficient than creating temporary files
When working with ZIP archives in Linux, a common requirement is to store a file under a different name than its original filename. The standard zip
command doesn't provide a direct flag for this operation, which often leads to workarounds like temporary file renaming.
Here are three reliable methods to achieve filename mapping during zipping:
Method 1: Using stdin redirection
cat file.txt | zip -mqj archive.zip -file2.txt
Explanation: The hyphen (-) indicates stdin input, while the filename after it specifies the stored name.
Method 2: Symbolic link approach
ln -s file.txt file2.txt
zip -mqj archive.zip file2.txt
rm file2.txt
Method 3: Advanced with pipe and printf
printf '@ -\n@=file2.txt\n' | zip -mqj archive.zip -file.txt
For production scripts, Method 1 is generally most reliable. Here's an enhanced version with error handling:
if ! cat file.txt | zip -mqj archive.zip -file2.txt; then
echo "Error: Failed to create archive" >&2
exit 1
fi
For complex scenarios, consider these alternatives:
# Using 7z (if installed)
7z a -tzip -siarchive_file2.txt archive.7z < file.txt
# Using Python
python3 -c "import zipfile; z=zipfile.ZipFile('archive.zip','w'); z.writestr('file2.txt',open('file.txt','rb').read())"