Shell – Compressing multiple files in different folders without folder structure

shell-scripttar

Currently I create a copy of my log files like this:

# tar -cvzf /var/www/vhosts/example.com/httpdocs/myfiles.tar.gz 
  /var/www/vhosts/example.com/logs/access_log       
  /var/www/vhosts/example.com/httpdocs/app/tmp/logs/error.log 
  /var/log/mysqld.log
  /var/log/messages 
  /var/log/httpd/access_log
  /var/log/httpd/suexec_log 
  /var/log/httpd/error_log 
  /var/log/sw-cp-server/error_log
  /usr/local/psa/var/log/xferlog
  /etc/php.ini 

But this creates a tar files with the directory structure. To avoid folder structure it seems like I should make cd for each file, so all files will be saved to tar file without subfolders. (Also there is a problem with tar.gz files, tar command doesn't permit to update archieve file, if file is compressed)

But in this case there will be multiple files with same name, for example 2 file with name access_log.

So I need to change destination log file name.
For example

/var/www/vhosts/example.com/logs/access_log   to  -var-www-vhosts-example.com-logs-access_log

/var/log/httpd/access_log  to   -var-log-httpd-access_log

Is this possible to archieve these files without the directory structure and with the file name changes ? Note that files exists in different folders.

Best Answer

Adding to @Marks answer

We can do it with the help of -T and --transform switches of tar command.

I have the directory structure as below.

|-- foo1
|   |-- file1.txt
|   |-- file2.txt
|   `-- file3.txt
|-- foo2
|   |-- file4.txt
|   |-- file5.txt
|   `-- file6.txt
|-- foo3
|   |-- file7.txt
|   |-- file8.txt
|   `-- file9.txt
`-- foo4
    |-- file10.txt
    |-- file11.txt
    `-- file12.txt

We can tar the files with directory name included

$ find -type f | tar --transform="s,/,-,2" -czvf compress.tgz -T -

And without directory name included.

$ find -type f | tar --transform="s,.*/,," -czvf compress.tgz -T -
Related Question