TheEditor
TheEditor

Reputation: 474

Naming tar archive the same as source file

Simply enough I want to create an archive from a file and preserve the file name.

File = host1.log
Tar  = Archive_date_host1.tar.gz

I'm using it like this:

find /var/log/TESTIN/ -daystart -mtime 7 -type f | xargs tar -czPf /var/log/TESTOUT/ARCHIVE_$(date +%F)_FILENAMEHERE.tar.gz

The "archive" and date portions I can do, but is there a way to grab the filename and use it? I've googled a bunch and can't seem to find anything.

Upvotes: 0

Views: 262

Answers (2)

Mark Plotnick
Mark Plotnick

Reputation: 10271

It looks like you want to use the basename of each file as the variable portion of the output file, that is, remove the directory portion of the name and the .log suffix. Try this:

find /var/log/TESTIN/ -daystart -mtime 7 -type f | \
xargs -I {} sh -c 'tar -czPf /var/log/TESTOUT/ARCHIVE_$(date +%F)_$(basename {} .log).tar.gz {}'

Upvotes: 1

Baris Demiray
Baris Demiray

Reputation: 1607

I think just find should be enough for that. For example, following command creates a .tar.gz archive out of every file found with the naming scheme you wanted. Note that {} is replaced by found file's name,

find * -type f -exec tar -czf ARCHIVE_$(date +%F)_{}.tar.gz {} \;

Upvotes: 1

Related Questions