【问题标题】:Compare two files and combine different columns of two files together into a single file using shell比较两个文件并使用 shell 将两个文件的不同列组合成一个文件
【发布时间】:2020-02-12 09:30:28
【问题描述】:

我有两个文件 file1.txt 和 file2.txt。

file1.txt

Amal=123=amal@gmail.com
Anil=342=anil@gmail.com
Ajith=548=ajith@gmail.com
Aravind=998=arav@gmail.com

file2.txt

Anil=Active
Amal=Active
Ajith=Inactive
Aravind=Active
Midhun=Active

我需要在 file2.txt 的 file1.txt 中添加一个额外的列,说明它们每个是活动的还是非活动的,并从 file2.txt 中删除 file1.txt 中不存在的行。(例如,Midhun 是file1.txt 中不存在。所以我需要从 file2.txt 中删除 midhun)

我的输出文件应该是

输出.txt

Amal=123=Active
Anil=342=Active
Ajith=548=Inactive
Aravind=998=Active

我尝试了以下方法。但它不起作用。

while IFS= read -r line    
do
    key=`echo $line | awk -F "=" '{print $1}'` < file1.txt
    key2=`echo $line | awk -F "=" '{print $2}'` < file1.txt
    value=`echo $line | awk -F "=" '{print $2}'` < file2.txt
    echo "$key=$key2=$value"
done

【问题讨论】:

  • 请在您的问题中将代码标签应用于您的样本和代码,然后让我们知道,因为这不清楚。

标签: shell


【解决方案1】:

编辑:由于 OP 改变了他的要求,所以现在添加这个解决方案。

awk '
BEGIN{
  FS=OFS="="
}
FNR==NR{
  a[$1]=$2
  next
}
($1 in a){
  $3=""
  sub(/=$/,"")
  print $0,a[$1]
}
'  Input_file2   Input_file1


这对awk来说应该是一个简单的任务,请尝试关注。

awk 'BEGIN{FS=OFS="="} FNR==NR{a[$1]=$2;next} ($1 in a){print $0,a[$1]}' file2 file1

说明:在此添加上述代码的详细说明。

awk '              ##Starting awk program from here.
BEGIN{             ##Starting BEGIN section for this program from here.
  FS=OFS="="       ##Setting FS and OFS value as = here for all lines.
}                  ##Closing BLOCK for BEGIN here.
FNR==NR{           ##Checking condition FNR==NR which will be TRUE when first Input_file is being read.
  a[$1]=$2         ##Creating array a with index $1 and value $2.
  next             ##next will skip all further statements from here.
}
($1 in a){         ##Checking condition ig $1 of current line(from file1) is present in array a then do following.
  print $0,a[$1]   ##Printing current line and value of array a with index $1 of current line here.
}
' file2 file1      ##Mentioning Input_file names here.

【讨论】:

  • 您好 RavinderSingh,感谢您的回复。我也试过这个命令。仍然没有得到。当我执行你的命令时,它甚至没有打印任何东西。
  • @AjinJoy,您是否将两个文件都传递给它?您的文件是否也具有与所示样本相同的数据?因为对我来说,这个命令对显示的样本很有效,请让我知道我的问题。
  • 嗨,RavindherSingh,我正在传递这两个文件。并具有与样本中所示相同的数据。你能给我这样的输出吗? Amal=123=Active Anil=342=Active Ajith=548=Inactive Aravind=998=Active
  • 从 output.txt 中删除该邮件 ID。只需打印“name=number=Status(Active/Inactive)”
  • @AjinJoy 对于您指定的文件内容,awk 命令输出您在问题中指定的输出。您确定要在正确的文件上测试命令吗?你是如何测试它的?
【解决方案2】:

无需编写脚本。对文件进行排序,然后这是一个简单的连接。

join -t= <(sort file1.txt) <(sort file2.txt)

为了遵守 OP 的更新,我们删掉 file1 的前两个字段:

join -t= <(sort file1.txt | cut -d= -f-2) <(sort file2.txt)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2015-08-12
  • 2020-12-29
  • 2013-05-30
相关资源
最近更新 更多