Renaming all files inside a zipped file

Hi,
To all the Unix gurus this should be a simple task, but as a newbie I'm finding it hard to crack this. Any help is highly appreciated...

Scenario:

Step 1 : Move zip file from FTP folder to WORK folder

Step 2:
Unzip the file "Sample_YYYYMMDDHHMMSS.tar.gz" which contains many file like a) Sample1.del
b) Sample2.del
c) Sample3.del etc...
Step 3: Rename all extracted files to
a) Sample1_YYYYMMDDHHMMSS.del
b) Sample2_YYYYMMDDHHMMSS.del
c) Sample3_YYYYMMDDHHMMSS.del

Thanks,

Andy

This is one way to rename the file(s):

## Rename files
dt=`date "+%Y%m%d%H%M%S"`
for x in `ls Sample*.del`
do
  nfn=${x%%.*}
  ext=${x##*.}
  mv $x ${nfn}$dt.$ext
done

Example:

x="Sample12.del"
dt=`date "+%Y%m%d%H%M%S"`
nfn=${x%%.*}
echo $nfn
ext=${x##*.}
echo $ext
echo mv $x ${nfn}_$dt.$ext

Sample12
del
mv Sample12.del Sample12_20130103155219.del

That is a Useless Use of ls

TS=$( date +"%Y%m%d%H%M%S" )
for file in Sample*.del
do
    mv $file ${file%.*}_${TS}.del
done

Step 1 & 2 are pretty much straightforward. You can use mv and tar -zxvf for moving and extracting.

Thanks spacebar for the prompt reply, but I think I didn't explain the requirement properly. The "YYYYMMDDHHMMSS" part of the Zip file name is kind a hard coded and we should use that value to rename all the file inside it.
Secondly the files inside the Zip file does not follow any pattern for example it may not be "sample1.del" and "sample2.del" but can be "abcd.del" and "nmhs.del"

tgz_file="Sample_20130101000000.tar.gz"

FN=$( echo ${tgz_file%%.*} )
TS=$( echo ${FN##*_} )

for file in *.del
do
        mv $file ${file%.*}_${TS}.del
done

Unnecessary sub-shells!

FN=${tgz_file%%.*}
TS=${FN##*_}

My bad, put echo to verify the results of trim and later embedded between parentheses. That is indeed unnecessary. Thanks for pointing that out. :b:

Thanks everybody for their valuable contribution, it worked...

I'm not sure why I'm getting this error

mv: 0653-401 Cannot rename *.del to *_20121220121212.del:
             A file or directory in the path name does not exist.
#!/usr/bin/ksh

gzip -c /home/asandy1234/Sample_20121220121212.tar > /home/asandy1234/Sample_20121220121212.tar.gz

SAMPLE_FILE="/home/asandy1234/Sample_20121220121212.tar.gz"

gzip -dc ${SAMPLE_FILE} |tar xf - 

tgz_file="/home/asandy1234/Sample_20121220121212.tar.gz"
echo "tgz_file"
FN=${tgz_file%%.*}
TS=${FN##*_}

for file in *.del
do
        mv $file ${file%.*}_${TS}.del
done

It does that because there are no files ending with .del in the current path. When that happens, the filename is taken literally as "*.del" instead of expanding into a list of filenames.

Thanks for the help, the problem was with the way .tar file was created( it had an extra folder structure)...

1 Like