Shell脚本:检查两个CSV文件中"X"列中的数据是否匹配 [英] Shell script: Check if data in columns `X` from two CSV files are matched
本文介绍了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
其中参数1
,2
和3
是列号.
比方说,some_script
只是对文件a.txt
和b.txt
中同一列中的数据进行了比较.
Let's say, the some_script
just did comparison between data in the same column from files a.txt
and b.txt
.
我需要一些用bash
,sed
或awk
编写的程序(或其他可能的程序)来完成这项工作.
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 $?
说明:
-
[ "string1" = "string2" ]
-测试命令.如果string1
等于string2
,则返回0
,否则返回1
.有关其他信息,请参见man test
. -
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 $?
.
-
[ "string1" = "string2" ]
- The test command. If thestring1
equals to thestring2
, it returns0
, else1
. Seeman test
for another information.cut -d' ' -f1 a.txt
- cut the first column from the filea.txt
.-d' '
- set the field delimiter to the space.-f1
- select only the field number1
. You can use a variable, instead of the number1
in this case, like thenum=1; [ "$(cut -d' ' -f$num a.txt)" = "$(cut -d' ' -f$num b.txt)" ]; echo $?
.
这篇关于Shell脚本:检查两个CSV文件中"X"列中的数据是否匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文