Shell脚本:检查两个CSV文件中"X"列中的数据是否匹配 [英] Shell script: Check if data in columns `X` from two CSV files are matched

查看:186
本文介绍了Shell脚本:检查两个CSV文件中"X"列中的数据是否匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有

a.txt:

1 21 34
1 22 21
2 32 76
2 12 76
...

b.txt:

1 99 73
1 32 27
2 55 76
2 76 12
...

预期输出:

$ ./some_script 1 a.txt b.txt
0 # matched
# compare data in #1 column of a.txt to data in #1 column of b.txt
# data: a.txt  b.txt
#       1      1
#       1      1
#       2      2
#       2      2
$ ./some_script 2 a.txt b.txt
1 # not matched
$ ./some_script 3 a.txt b.txt
1 # not matched

其中参数123是列号.

比方说,some_script只是对文件a.txtb.txt中同一列中的数据进行了比较.

Let's say, the some_script just did comparison between data in the same column from files a.txt and b.txt.

我需要一些用bashsedawk编写的程序(或其他可能的程序)来完成这项工作.

I need some program written in either bash, sed, or awk (or another possible programs) to do this job.

推荐答案

[ "$(cut -d' ' -f1 a.txt)" = "$(cut -d' ' -f1 b.txt)" ]; echo $?

说明:

  1. [ "string1" = "string2" ]-测试命令.如果string1等于string2,则返回0,否则返回1.有关其他信息,请参见man test.
  2. cut -d' ' -f1 a.txt-从文件a.txt中剪切第一列.
    • -d' '-将字段定界符设置为空格.
    • -f1-仅选择字段编号1.在这种情况下,您可以使用变量而不是数字1,例如num=1; [ "$(cut -d' ' -f$num a.txt)" = "$(cut -d' ' -f$num b.txt)" ]; echo $?.
  1. [ "string1" = "string2" ] - The test command. If the string1 equals to the string2, it returns 0, else 1. See man test for another information.
  2. cut -d' ' -f1 a.txt - cut the first column from the file a.txt.
    • -d' ' - set the field delimiter to the space.
    • -f1 - select only the field number 1. You can use a variable, instead of the number 1 in this case, like the num=1; [ "$(cut -d' ' -f$num a.txt)" = "$(cut -d' ' -f$num b.txt)" ]; echo $?.

这篇关于Shell脚本:检查两个CSV文件中"X"列中的数据是否匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆