سؤال

In past I have used following command to archive old files to one file

find . -mtime -1 | xargs tar -cvzf archive.tar

Now suppose we have 20 directories I need to make a script that goes in each directory and archives all files to different files which have same name as original file?

So suppose if I have following files in one directory named /Home/basic/ and this directory has following files:

first_file.txt
second_file.txt
third_file.txt

Now after I am done running the script I need output as follows:

first_file_05112014.tar
second_file_05112014.tar
third_file_05112014.tar
هل كانت مفيدة؟

المحلول

Use:

find . -type f -mtime -1 | xargs -I file tar -cvzf file.tar.gz file

I added .gz to indicate its zipped as well.

From man xargs:

 -I replace-str
     Replace occurrences of replace-str in the initial-arguments with names
     read from standard input.  Also, unquoted blanks do not terminate input
     items; instead the separator is the newline character.  Implies -x and -L 1.

The find command will produce a list of filepaths. -L 1 means that each whole line will serve as input to the command.

-I file will assign the filepath to file and then each occurrence of file in the tar command line will be replaced by its value, that is, the filepath.

So, for ex, if find produces a filepath ./somedir/abc.txt, the corresponding tar command will look like:

tar -czvf ./somedir/abc.txt.tar.gz ./somedir/abc.txt

which is what is desired. And this will happen for each filepath.

نصائح أخرى

What about this shell script?

#!/bin/sh

mkdir /tmp/junk  #Easy for me to clean up!
for p in `find . -mtime -1 -type f`
do
    dir=`dirname "$p"` 
    file=`basename "$p"`
    tar cvf /tmp/junk/${file}.tar $p
done

It uses the basename command to extract the name of the file and the dirname command to extract the name of the directory. I don't actually use the directory but I left it in there in case you might find it handy.

I put all the tar files in one place so I could delete them easily but you could easily substitute $P instead of $file if you wanted them in the same directory.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top