Ray
Ray

Reputation: 797

Bash: How to grep in a list of files (some of which are zip files)

I have a list of files i search for at high level, some .txt and some .gz

Each file is a text file under the hood.

Is there a command to find a obtain the list and grep each file? My attempt thusfar

find $(pwd) -name "instr.txt" -o -name "instr.txt.gz"

Upvotes: 0

Views: 406

Answers (2)

Aaron
Aaron

Reputation: 24802

zgrep will successfully search patterns in both plain text files and gz-archived files, so the following command should work fine :

find . \( -name "instr.txt" -o -name "instr.txt.gz" \) -exec zgrep searchedPattern {} +

A few notes :

  • depending on the number of matched files, zgrep will or will not output the file name in addition to the matched lines. Use -H to force their presence or -h to force their absence.
  • I've replaced the $(pwd) subshell by the equivalent relative path ., but this will impact the filenames in the output. If you need to output absolute pathes, using your subshell is fine.
  • You need parenthesis to group the two sides of your -o, otherwise the action is only executed for the rightmost side. A less portable alternative would be to use -regex 'instr.txt\(.gz\)?'

Upvotes: 1

Jason
Jason

Reputation: 2671

Assuming you are not doing this recursively (not searching through sub-directories), here is a simple solution that does not use find...

grep "insert pattern here" *.txt

for filename in *.gz; do
  zgrep "insert pattern here" "$filename"
done

Upvotes: 0

Related Questions