【问题标题】:Unix script. How can I search for a keywords in a file and another one remove the entire line?Unix 脚本。如何在文件中搜索一个关键字而另一个关键字删除整行?
【发布时间】:2021-03-13 12:52:22
【问题描述】:

我是这方面的新手,非常感谢任何帮助。 我需要编写一个 Unix 代码来搜索文件 X 中的字符串,然后在文件目标中搜索删除之前找到的行...

我做了几次类似下面的尝试,但都没有成功。

grep -v "Invalid key: " issues.txt > translate1.stf ; mv translate1.stf  issues.txt

最好的问候, 乙

enter image description here

【问题讨论】:

  • 请在您的问题中添加示例输入(无描述、无图像、无链接)以及该示例输入所需的输出(无评论)。
  • 请不要发布文字图片;见meta.stackoverflow.com/questions/303812/…
  • 看起来您正在尝试删除任何带有“无效密钥:”的行,如果是这种情况。你最好使用一个命令,即 sed。
  • 即使从您的图像中也不清楚您想要实现什么。输入包含类似Invalid key: CustomLabel.Something. Some error message. 的行。标记了CustomLabel.Something. 部分,但这与(不清楚)描述“第一个点和第二个点之后的此信息”不匹配。请在您的问题中澄清相关字符串是什么。图片显示“我必须在另一个文件中搜索此信息”在您的问题中还显示此“另一个文件”。和“如果存在我必须删除整行”。从图像中显示的文件?来自其他文件?
  • 我想我理解您的要求。您想删除 fileX 中“无效密钥:”和下一个句点 ('.') 之间的字符串包含在 fileY 中的任何行。听起来对吗?

标签: bash unix git-bash


【解决方案1】:

如果我理解您的要求,您想删除 fileX 中“无效密钥:”和下一个句点 ('.') 之间的字符串包含在 fileY 中的任何行。

这可以在awk 中完成。

如果 fileX 被命名为“input.txt”并且包含

Line 1
Invalid Key: Key1. this line shows
Line 2
Invalid Key: Key2. this line is filtered
Invalid Key: Key3. this line is filtered
Invalid Key: Key4. this line shows
Line 3

fileY 被命名为“keysToFilter.txt”

# lines containing these keys are deleted
Key2
Key3

和文件“过滤器”中的一个程序

#! /usr/bin/awk -f

BEGIN {
  while (getline < "keysToFilter.txt") {
    keys[$0] = 1
  }
}

# lines matching 'Invalid Key' get this treatment
/^Invalid Key: / {
  keyStart = length("Invalid Key: ") + 1
  keyEnd = index($0, ".")
  key = substr($0, keyStart, keyEnd - keyStart)
  if ( !(key in keys) ) {
    print $0
  }
  next 
}

# every other line is unfiltered  
{ print }

... 那么下面的内容会将fileX 的过滤版本发送到stdout

$ cat input.txt | ./filter

【讨论】:

  • 对不起,可能不清楚。我会再试一次。我有两个文件。第一个我可以找到所有内容,第二个是日志文件错误...例如:FileX(所有事物)FileLogError(FileX 中的无效键)所以我必须能够从 FileLogError 中搜索行在 FileX 中,如果找到,我必须删除整行。是不是更清楚了?非常感谢!!
  • 再解释:FileX Value 1 - Label value 1 Value 2 - Label value 2 Value 3 - Label value 3 Value 4 - Label value 4 Value 5 - Label value 5 FileLogError Invalid key: "Label value 2" 无效键:"标签值 5" 我必须能够清理 FileX,最后会是这样。 FileX 值 1 - 标签值 1 值 3 - 标签值 3 值 4 - 标签值 4
  • 我可以建议您编辑您的问题,而不是使用 cmets 添加额外的解释吗?将 2 个文件的示例内容放在单独的块中,就像我对答案所做的那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2015-01-01
相关资源
最近更新 更多