Reputation: 717
I have n numbers of zip files in a directory. inside these zip files, there is space in the beginning of file name. I just want to remove this space without extracting the zip file.
I tried a shell script, as below.
#!/bin/sh
for zip in *.zip
do
unzipped=unzip $zip
trimmed=echo "${unzipped}" | sed -e 's/^[ \t]*//'
#Want to zip the file here with the same name
done
Need help in this script or if any short method will be most welcome.
Upvotes: 1
Views: 833
Reputation: 876
You could use the tool zipnote
which is part of Info-ZIP's zip package. Based on your code example above, a minimal working example could look like this:
#!/bin/bash
for zip in *.zip
do
ZIPNOTES=$(zipnote "$zip")
TRIMMED=$(echo "$ZIPNOTES" | sed -e 's/^@[ \t]\{2,\}\(.*\)/&\n@=\1/')
echo "$TRIMMED" | zipnote -w "$zip"
done
or as one-liner:
#!/bin/bash
for zip in *.zip; do zipnote "$zip" | sed -e 's/^@[ \t]\{2,\}\(.*\)/&\n@=\1/' | zipnote -w "$zip"; done
Let's assume you have a zip archive archive.zip
containing the files \ \ foo
and bar
, the utility zipnote
outputs the following lines:
$ zipnote archive.zip
@ foo
@ (comment above this line)
@ bar
@ (comment above this line)
@ (zip file comment below this line)
According to man zipnote
:
The names of the files in the zipfile can also be changed in this way. This is done by following lines like "@ name" in the created temporary file (called foo.tmp here) with lines like "@=newname" and then using the -w option as above.
Hence, to rename the file \ \ foo
within the zip archive, you have to append the line
@=foo
just beneath the corresponding line
@ foo
and pipe it into zipnote -w archive.zip
. The latter is done with a slight modification of your sed
command which matches on lines containing an @
symbol followed by two or more whitespaces, grouping the rest of the line and appending the trimmed line beneath.
Upvotes: 3