搜索特定单词并仅在单独的文件中打印这些单词

时间:2015-06-30 12:37:53

标签: shell unix

我的Unix服务器上有一个.gz文件。我想从该文件中搜索两个单词,如abc123def456,如果我在文件中有这些单词,我想只打印那些单词(只有2个单词而不是整行)单独的单词文件。

4 个答案:

答案 0 :(得分:0)

You can try the following:

zcat f.xml.gz | awk '{\
{ \
if(index($0,str_1)) \
   cnt_1=1; \
if(index($0,str_2)) \
   cnt_2=1; \
if((cnt_1 + cnt_2) == 2) {\
   print str_1,str_2> "f_out.log"; exit;} \
} }' str_1="Keepout" str_2="LatLonList"

where

  • "f.xml.gz" is the input file
  • str_1 is the first word (your "abc123")
  • str_2 is the second word (your "def456")
  • "f_out.log" is the separate file in which the two words are written if found in the input file

Hope this helps.

答案 1 :(得分:0)

您的问题有答案in this SO post

您可以运行此命令来实现您想要的目标

gzcat <filename.zip> | grep -oh "<Search pattern>" *

for ex

gzcat <filename.zip> | grep -oh "abc123" * 

我没有安装zgrep,但你也可以试试这个

zgrep -oh "<Search pattern>" *` filename.zip

答案 2 :(得分:0)

ripgrep

使用ripgrep,它在Rust中写得非常有效,特别是对于大文件。例如:

rg -zo "abc123|def456" *.gz
  

-z / --search-zip搜索压缩文件(例如gzbz2xzlzma)。

     

-o / --only-matching仅打印匹配行的匹配部分。

答案 3 :(得分:0)

grep / zgrep / zegrep

使用zgrepzegrep使用未压缩的内容(GNU / Linux和BSD / Unix)查找压缩文件中的模式。

在Unix上,您还可以将grepBSD version)与-Z一起使用,包括macOS上的-z

几个例子:

zgrep -E "abc123|def456" *.gz
zegrep "abc123|def456" **/*.gz
grep -z -e "abc123" -e "def456" *.gz # BSD/Unix only.

注意:当您globbing option enabled时,**会递归检查文件,否则请使用-r

  

-R / -r / --recursive递归搜索列出的子目录。

     

-E / --extended-regexp将模式解释为扩展正则表达式(如egrep)。

     

-ZBSD),-z / --decompressBSD/macOS)强制grep表现为zgrep

相关问题