shell - 在 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
解决方案
你能试着关注一次吗?仅使用提供的样品进行测试。
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
推荐阅读
- python - 如何模拟 PLC 服务器 (CIP),以便我们可以使用 pycomm3 连接到它?
- pygame - 在pygame中,释放按钮时vaw文件会中断
- javascript - 父更新子时不调用ngOnChange
- javascript - 是否可以扭曲 SVG 圆圈?
- reactjs - 在功能组件中调用 API
- sql - 寻找相同的交易者在 3 分钟内购买和出售相同的产品
- ios - DispatchQueue.main.async 导致搜索挂起。迅速
- google-bigquery - 如何知道 bigquery 表中的最小集群大小?
- r - 多个图形命令在 R 图中不起作用?
- python - python kivy 背景颜色变白