Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing grep operation in tar files without extracting

Tags:

unix

I have list of files which contain particular patterns, but those files have been tarred. Now I want to search for the pattern in the tar file, and to know which files contain the pattern without extracting the files.

Any idea...?

like image 632
Pavunkumar Avatar asked Mar 09 '10 06:03

Pavunkumar


People also ask

Can we grep in tar file?

On the other side, the grep command has the –label=LABEL option to display LABEL as the filename. It's pretty useful when we grep on Stdin. Therefore, to solve the problem, we can assemble a command like tar … –to-command='grep …' and pass tar's TAR_FILENAME variable to grep's –label option. It works!

How can I view the contents of a tar file without extracting it?

Use -t switch with tar command to list content of a archive. tar file without actually extracting. You can see that output is pretty similar to the result of ls -l command.

How do I grep text in a gz file?

You need to use zgrep command which invokes grep on compressed or gzipped files. All options specified are passed directly to the grep command or egrep command.

What is the difference between grep and zgrep?

zgrep states it works the same as grep, but can handle zipped files. zgrep "hello" * however returns 1 even though the pattern was found in test1. it returns 1 because the pattern was not found in test2. turns out if any file does not match the pattern, 1 is returned, even if all other files do match the pattern.


1 Answers

the tar command has a -O switch to extract your files to standard output. So you can pipe those output to grep/awk

tar xvf  test.tar -O | awk '/pattern/{print}'  tar xvf  test.tar -O | grep "pattern" 

eg to return file name one pattern found

tar tf myarchive.tar | while read -r FILE do     if tar xf test.tar $FILE  -O | grep "pattern" ;then         echo "found pattern in : $FILE"     fi done 
like image 170
ghostdog74 Avatar answered Nov 11 '22 18:11

ghostdog74