bash - 如何查找和压缩包含字符串的文件?

时间:2017-07-27 03:02:12

标签: bash

我想将包含字符串'12345'的所有文件压缩到文件mylog.zip。 使用grep -l我可以找到该文件并使用此命令,但它不会压缩文件。

grep -l 12345  *  |  zip  mylog.zip; 

我尝试命令

grep -l 12345  *

找到了文件。问题是如何将其传递给zip。

2 个答案:

答案 0 :(得分:1)

find -name "*12345*" -type f -print | zip name.zip -@

OR

find -name "*12345*" -type f -exec zip name.zip {} +

答案 1 :(得分:1)

另一个使用bash for循环。如果需要,在变量周围添加适当的引用。在这个例子中,我在一堆文件中grep a

$ for f in *.txt; do grep -q a $f; if [ $? -eq 0 ]; then zip my.zip $f ; fi ; done
  adding: test1.txt (stored 0%)
  adding: test3.txt (stored 0%)

写得开放:

for f in *.txt
do 
    grep -l a $f
    if [ $? -eq 0 ]
    then 
        zip my.zip $f
    fi
done
相关问题