首页 > 解决方案 > 在 awk 中比较 2 个文件

问题描述

我有 2 个输入文件,如下所示。

File1

India USA China Russia France England

File2

India
USA
China
Russia
France
England

我需要验证文件 2 中的所有列是否以相同的顺序在文件 1 中可用。在 awk 脚本(ksh)中实现这一目标的有效方法是什么

我编写了一个示例脚本,如下所示。但是,我想知道简单有效的解决方案。

#!/bin/ksh
        i=1
while read line
do
        val=`cat File1 | cut -d" " -f$i`
        echo $val $line

        if [ $val = $line ]
        then
                echo "Matches"
        else

                echo "Not matches"
        fi
        i=$((i+1))
done < ./File2

标签: shellunixawkksh

解决方案


你能试着关注一次吗?仅使用提供的样品进行测试。

awk '
{
  sub(/[[:space:]]+$/,"")
}
FNR==NR{
  a[FNR]=$0
  next
}
{
  for(i=1;i<=NF;i++){
    count=a[i]==$i?++count:count
  }
  if(count==length(a)){
    print "Line number " FNR " whose contents are:" $0 " present in both the files."
  }
  count=""
}'   Input_file2   Input_file1

输出如下。

Line number 1 whose contents are:India USA China Russia France England present in both the files.

如果您的字符串可能在其值中包含大写或小写字母,现在添加可以解决该问题的解决方案。

awk '
{
  sub(/[[:space:]]+$/,"")
}
FNR==NR{
  a[FNR]=tolower($0)
  next
}
{
  for(i=1;i<=NF;i++){
    count=a[i]==tolower($i)?++count:count
  }
  if(count==length(a)){
    print "Line number " FNR " whose contents are:" $0 " present in both the files."
  }
  count=""
}'  Input_file2   Input_file1

或者如在其他条件下的聊天代码中讨论的那样。

awk '
{
  sub(/[[:space:]]+$/,"")
}
FNR==NR{
  a[FNR]=tolower($0)
  next
}
{
  for(i=1;i<=NF;i++){
    count=a[i]==tolower($i)?++count:count
  }
  if(count==length(a)){
    print "Line number " FNR " whose contents are:" $0 " present in both the files."
  }
  else{
    print "Line number " FNR " is NOT matching..."
  }
  count=""
}'  Input_file2   Input_file1

推荐阅读