Hi,
I'm desperately in search for a solution of the following problem:
I have a directory full of zip-files. All these zip-files contain a single file with a name that should be used for the name of the zip-container.
Anybody a good idea. I'm an absolute beginner in shell scripting - so please bear with me.
$ cat mark.sh
for zip in *.zip
do
file="$(unzip -l -qq "${zip}" | sed 's/.*:[0-9]\+[[:space:]]*//')"
newzip=$(echo "${file}" | sed 's/ /_/g').zip
echo "Zip '${zip}' contains file '${file}', renamed to '${newzip}'"
mv ${zip} ${newzip}
done
exit
$ ./mark.sh
Zip 'm1.zip' contains file 'mark_1', renamed to 'mark_1.zip'
Zip 'm2.zip' contains file 'mark_2.txt', renamed to 'mark_2.txt.zip'
Zip 'm3.zip' contains file 'mark with spaces', renamed to 'mark_with_spaces.zip'
$
Sorry,
my description was not entirely correct. Alle zip-files contain a large amount of files but always a file with the name ########.jdf,
where ######## is always a 8-digit number. That filename should be used as the zipfiles name. I suppose that makes it a little bit more complicated.
Is 'sed' still the way to go or is 'grep' more suitable?
for zip in *.zip
do
jdf="$( unzip -l -qq "${zip}" |
sed -n 's/.*:[0-9]\+[[:space:]]*\([0-9]\{8\}\)\.jdf$/\1/p')"
if [ -z "${jdf}" ]
then
echo "Invalid zip file '${zip}', jdf file not found"
continue
fi
newzip=${jdf}.zip
echo "Zip '${zip}' contains file '${jdf}.fdf', renamed to '${newzip}'"
mv ${zip} ${newzip}
done
exit
$ ./mark.sh
Zip 'm1.zip' contains file '12345678.fdf', renamed to '12345678.zip'
Zip 'm2.zip' contains file '87654321.fdf', renamed to '87654321.zip'
Invalid zip file 'm3.zip', jdf file not found
$
The folllowing new version of the script handles file names with directory specification. The output of your unzip command isn't a problem.
for zip in *.zip
do
jdf=$( unzip -l -qq "${zip}" |
sed -n 's=.*[/ ]\([0-9]\{8\}\)\.jdf[ ]*$=\1=p' )
if [ -z "${jdf}" ]
then
echo "Invalid zip file '${zip}', jdf file not found"
continue
fi
newzip=${jdf}.zip
echo "Zip '${zip}' contains file '${jdf}.jdf', renamed to '${newzip}'"
mv ${zip} ${newzip}
done
exit
If the sed command doesn't work, try this modification :
$ ./mark2.sh
Zip 'm1.zip' contains file '12345678.jdf', renamed to '12345678.zip'
Zip 'm2.zip' contains file '87654321.jdf', renamed to '87654321.zip'
Invalid zip file 'm3.zip', jdf file not found
$