text - awk - 比较两个文件,匹配一个字段,合并两个文件

标签 text awk

嘿伙计们,我需要一些帮助,
我的目标是在 file2 中匹配 find 或匹配 file1 的第一部分

文件1:

\\tempcomputer\c$\test2;test folder;c:\test2
\\tempcomputer\c$\temp;temp folder;C:\temp
\\tempcomputer\c$\unavailablefolder;c:\unavailablefolder

文件2:
\\tempcomputer\c$\test2\;2.777.768 Bytes;11/09/12;11/09/12
\\tempcomputer\c$\temp\;5.400.050.974 Bytes;10/09/12;11/09/12
Error: Invalid property element: \\tempcomputer\c$\unavailablefolder

预期输出:
\\tempcomputer\c$\test2;test folder;c:\test2;2.777.768 Bytes;11/09/12;11/09/12
\\tempcomputer\c$\temp;temp folder;C:\temp;5.400.050.974 Bytes;10/09/12;11/09/12
\\tempcomputer\c$\unavailablefolder;c:\unavailablefolder;Error: Invalid property element: \\tempcomputer\c$\unavailablefolder

例如,我想从 file1 的第一行进行比较:
\\tempcomputer\c$\test2 

在第二个文件上搜索,并从 file1 连接两个文件
\\tempcomputer\c$\test2;test folder;c:\test2 

并从文件2
c:\test2;2.777.768 Bytes;11/09/12;11/09/12

所以第一行是:
\\tempcomputer\c$\test2;test folder;c:\test2;2.777.768 Bytes;11/09/12;11/09/12

第一行的预期结果:
\\tempcomputer\c$\test2;test folder;c:\test2;2.777.768 Bytes;11/09/12;11/09/12 

第二行的预期结果:
\\tempcomputer\c$\temp;temp folder;C:\temp;5.400.050.974 Bytes;10/09/12;11/09/12

第三行的预期结果:
\\tempcomputer\c$\unavailablefolder;c:\unavailablefolder;Error: Invalid property element: \\tempcomputer\c$\unavailablefolder

最佳答案

如果它是 c00kiemon5ter 指示带有反斜杠的复制粘贴错误,则只需遍历 File2 即可。 File1 中的每一行,我假设您在找不到匹配项时不希望输出。

简单的.awk

BEGIN { FS = OFS = ";" }

{ 
  l=$0
  first=$1
  while(getline < "File2") { 
    if(first == $1) {
      print l, $0
      break
    }
  }
}

运行:
awk -f simple.awk File1

最后允许一个可选的反斜杠需要更多的工作,但是大部分额外的复杂性可以转移到一个函数中:

更多工作.awk
function optional_end(s, c) {
  if(c == "")
    c = "\\"
  if(substr(s, length(s)) == c)
    s = substr(s, 1, length(s) - 1)
  return s
}

BEGIN { FS = OFS = ";" }

{ 
  l=$0
  first = optional_end($1)

  while(getline < "File2") {
    if(first == optional_end($1)) {
      print l, $0
      break
    }
  }
}

运行:
awk -f more-work.awk File1

由 c00kiemon5ter 编辑:3

修改了 simple.awk。
\; 合作first-field-line-endings 和 prints-joins 第三行。
BEGIN { FS = OFS = ";"; if( file == "") file = "File2" }

{ 
  l=$0
  first=$1
  while(getline < file) { 
    if((idx = index($0, first))) {
      if (idx == 1)
          $1 = l
      else
          $1 = l FS $0
      print
      break
    }
  }
}

编辑 2

输入文件现在可以作为选项给出 -v file=SOME_FILE ;如果没有给出“File2”,则使用,例如:
awk -f simple.awk -v file=SOME_FILE File1

关于text - awk - 比较两个文件,匹配一个字段,合并两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379564/

相关文章:

jquery - 如何使用 jquery 将文本添加到现有的 div

移动键盘上字母数字的html 5输入类型

java - 如何使用Java突出显示文档中的文本?

c# - 单击多个文本框的事件

linux - 你如何比较 linux 中两列之间的条目?

Android - 单选按钮不显示其文本

regex - 删除仅包含特定字符串的重复行

bash - 使用 grep/awk/UNIX 以列格式解析股票和价格的修复日志

regex - 用于在文本文件中搜索列的正则表达式

linux - 如何使用awk读取每n个字符而不是每行的文件?