Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use grep -lr output to add files to tar

In UBUNTU and CENTOS.

I have some files I want to tar based on their contents.

$ grep -rl "123.45" .

returns a list of about 10 files in this kind of format:

./somefolder/someotherfolder/somefile.txt
./anotherfolder/anotherfile.txt

etc...

I want to tar.gz all of them.

I tried:

$ grep -rl "123.45" . | tar -czf files.tar.gz

Doesn't work. That's why I'm here. Any ideas? Thanks.

Just tried this, and it worked in Ubuntu, but in CentOS I get "tar: 02: Cannot stat: No such file or directory".

$ tar -czf test.tar.gz `grep -rl "123.45" .`

If anyone else has a better way, let me know. That above one works great in Ubuntu, at least.

like image 407
Buttle Butkus Avatar asked Dec 27 '22 12:12

Buttle Butkus


2 Answers

Like this:

 ... | tar -T - -czf files.tar.gz

"-T -" causes tar to read filenames from stdin. Second minus stands for stdin. –

like image 198
Leonid Volnitsky Avatar answered Dec 29 '22 01:12

Leonid Volnitsky


grep -rl "123.45" . | xargs tar -czf files.tar.gz
like image 25
knesenko Avatar answered Dec 29 '22 02:12

knesenko