【问题标题】:filter out content between two files过滤掉两个文件之间的内容
【发布时间】:2016-08-31 02:54:37
【问题描述】:

我有两个文件

条件.txt

abcd
efgh

logs.txt

efgh
ijkl
mnop
qrst

我期望输出是:

ijkl
mnop
qrst

实际输出:

efgh
ijkl
ijkl
mnop
mnop
qrst
qrst

这是我到目前为止工作的代码

func(){
while read condition
do
if [[ $line = $condition ]] ; then
:
else
echo "$line";
done < condition.txt
}

while read line
do
func $line
done < log.txt

【问题讨论】:

  • 您的代码每次与condition.txt 文件中的任何一行不匹配时都会打印测试行。如果您向condition.txt 添加了另外两行(例如pqrstwxyz),您会看到除abcd 之外的每一行出现4 次(您会看到3 次出现)。只有当它与condition.txt 中的任何行都不匹配时,您才应该打印该行。但是在答案中使用fgrep(或grep -F)的建议要好得多。

标签: linux shell unix ubuntu filter


【解决方案1】:

尝试使用 grep:

$ grep -v -f conditions.txt logs.txt

来自 GNU grep 的手册页:

-v, --invert-match
          Invert the sense of matching, to select non-matching lines.

-f FILE, --file=FILE
          Obtain patterns from FILE, one per line.  If this option is used multiple times or is combined with the -e (--regexp)  option,  search  for  all  patterns
          given.  The empty file contains zero patterns, and therefore matches nothing.

【讨论】:

  • 如果需要精确(整行)匹配,您可以添加-x。用例句的话,就不是很清楚了。
  • 谢谢你,我期待同样的答案,但我想将 $line 的一部分(只有 $8,它有 $1 到 $8)与 $command 进行比较。有办法吗?
  • @user1934439 - 此评论似乎与您在问题中提供的示例输入不匹配。如果您可以提供更完整的样本输入集,则可能更容易弄清楚您想要什么。此答案涵盖了您当前问题中的所有内容,并解释了它是如何作为额外奖励工作的。
  • 对不起,我不明白你的评论@user1934439,你能详细说明一下吗?
【解决方案2】:

如果你不想重新发明轮子……

grep -vf conditions.txt logs.txt 
ijkl
mnop
qrst

【讨论】:

  • 谢谢你,我期待相同的答案,但我想将 $line 的一部分(它有 $1 到 $8)与 $command 进行比较。有办法吗?
  • @user1934439 - 您可能想为此修改您的问题/示例代码......输入与您发布的内容完全不匹配。
猜你喜欢
  • 2020-07-15
  • 2011-12-03
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
相关资源
最近更新 更多