1

Is there any easy way extract all files from a .tar.gz and rename the files upon extraction? The tars inside look like:

file1.obj
file2.xr
file3.ty
file4.hjg

All files are different extensions, but I want extract them and rename them the same, so the extracted files would be

name.obj
name.xr
name.ty
name.hjg

I know the names of all these files, and their extensions, are constant for all tar balls. I could easily extract them and then rename them after by searching for their name but that would be a heavy operation, is there an easier way? Here's my python script code

# GRAB DATES
#   range : 2010 - 2011
start_date = datetime(2010, 01, 01)
end_date = datetime(2011, 12, 31)

for date in daterange(start_date, end_date):
    file_append = static_path + "%04d" % date.year + "%02d" % date.month + "%02d" % date.day + ".tar.gz" 
    file_out = "%04d" % date.year + "%02d" % date.month + "%02d" % date.day

    # get tarball from site
    proc_wget = "wget -nd -O " + "%04d" % date.year + "/" + file_out + \
            ".tar.gz" + " http://water.weather.gov/precip/p_download_new/" + \
            "%04d" % date.year + "/" + "%02d" % date.month + "/" + \
            "%02d" % date.day + "/" + file_append

    # name of tarball is file_out + ".tar.gz" 
    # all files inside tarbal are static_name.*
    # so they all have the same name but different extensions
    extract = ["7z e " + file_out + ".tar.gz", 
               "7z x " + file_out + ".tar -o" ]
    os.system(proc_wget)
    os.system(extract[0])
    os.system(extract[1])

1 Answer 1

1

This should do the job:

$ tar -xzvf foo.tar && cd foo
$ for i in *; do echo $i |sed -re "s/[A-Za-z0-9]+(.*)/name\1/"; done

To do this in Python call:

new_str = re.sub('[A-Za-z]+(.*)', r'\name\1', old_str);

Here's another:

$ for i in *; do echo name.${i#*.}; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.