Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find string inside a gzipped file in a folder

My current problem is that I have around 10 folders, which contain gzipped files (around on an average 5 each). This makes it 50 files to open and look at.

Is there a simpler method to find out if a gzipped file inside a folder has a particular pattern or not?

zcat ABC/myzippedfile1.txt.gz | grep "pattern match" zcat ABC/myzippedfile2.txt.gz | grep "pattern match" 

Instead of writing a script, can I do the same in a single line, for all the folders and sub folders?

for f in `ls *.gz`; do echo $f; zcat $f | grep <pattern>; done; 
like image 362
gagneet Avatar asked Aug 10 '09 08:08

gagneet


People also ask

How do I search for a string in a folder?

Finding text strings within files using grep-r – Recursive search. -R – Read all files under each directory, recursively. Follow all symbolic links, unlike -r grep option. -n – Display line number of each matched line.

How do I search for a string in a GZ file?

Grep gz files without unzipping As we showed earlier, you can use the zgrep command to search through compressed files without having to unzip them first. You can also use the zcat command to display the contents of a gz file and then pipe that output to grep to isolate the lines containing your search string.

How do I grep a string into a GZ file?

Unfortunately, grep doesn't work on compressed files. To overcome this, people usually advise to first uncompress the file(s), and then grep your text, after that finally re-compress your file(s)… You don't need to uncompress them in the first place. You can use zgrep on compressed or gzipped files.

How do I open a .GZ file without extracting it?

Just use zcat to see content without extraction. From the manual: zcat is identical to gunzip -c . (On some systems, zcat may be installed as gzcat to preserve the original link to compress .)


2 Answers

zgrep will look in gzipped files, has a -R recursive option, and a -H show me the filename option:

zgrep -R --include=*.gz -H "pattern match" . 

OS specific commands as not all arguments work across the board:

Mac 10.5+: zgrep -R --include=\*.gz -H "pattern match" .

Ubuntu 16+: zgrep -i -H "pattern match" *.gz

like image 110
Ned Batchelder Avatar answered Sep 28 '22 01:09

Ned Batchelder


You don't need zcat here because there is zgrep and zegrep.

If you want to run a command over a directory hierarchy, you use find:

find . -name "*.gz" -exec zgrep ⟨pattern⟩ \{\} \; 

And also “ls *.gz” is useless in for and you should just use “*.gz” in the future.

like image 37
Nietzche-jou Avatar answered Sep 28 '22 03:09

Nietzche-jou