如果没有结果,如何停止grep创建空文件 [英] how to stop grep creating empty file if no results

查看:378
本文介绍了如果没有结果,如何停止grep创建空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 grep -v -f file1.txt file2.txt>比较两个文件中不在另一个文件中的行的结果。 result.txt



假设我的文件看起来像这样;



file1.txt

  alex 
peter
zoey
$ b $ file2.txt

  alex 
john
peter
zoey

所以 result.txt 应该包含 john



这是在Jenkins工作中运行的,jenkins最终不开心创建一个空的 result.txt ,如果两者没有区别的话。



我不能只做一个盲差异/无差异输出,我特别需要知道哪些行有差异。



如果没有结果,是否有更简单的方法来运行此命令不创建文件?

解决方案

<编辑:尝试有条件地运行带有安静选项-q的命令(当找到一个匹配并保存时间时,它将退出)。然后,一旦找到第一个匹配项(意味着文件不同),您将运行相同的命令并将其输出到您的文件。

试试这个:(编辑采自查尔斯杜菲的评论)

  #!/ usr / bin / env bash 

if grep -qvf file1.txt file2.txt
then
grep -vf file1.txt file2.txt> output.txt
echo存在差异,创建文件output.txt。
else
echo检测到的文件没有区别
fi



<

  grep -qvf file1.txt file2.txt&& grep -vf file1.txt file2.txt> output.txt 


I'm comparing the results of two files for lines in one that are not in the other using grep -v -f file1.txt file2.txt > result.txt

Let's say my files look like;

file1.txt

alex
peter
zoey

file2.txt

alex
john
peter
zoey

So result.txt should contain john

This is to be run inside a Jenkins job, and jenkins ends up not happy with creating an empty result.txt if there are no differences between the two.

I can't just do a blind diff/no diff output, I specifically need to know which lines differ if there are any.

Is there a neater way to run this command to not create a file if there are no results?

解决方案

EDIT: Try conditionally running the command with the quiet option -q (which will exit when one match is found and save time). Then once the first match is found (meaning the files are different), you will run the same command and output it to your file.

Try this: (EDIT taken from Charles Duffy's comment)

#!/usr/bin/env bash

if grep -qvf file1.txt file2.txt 
then
   grep -vf file1.txt file2.txt > output.txt
   echo "Differences exist. File output.txt created." 
else
   echo "No difference between the files detected"
fi

Or with less code and one line:

grep -qvf file1.txt file2.txt && grep -vf file1.txt file2.txt > output.txt

这篇关于如果没有结果,如何停止grep创建空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆