如何在Linux中比较两列之间的条目?

时间:2019-06-13 01:24:52

标签: linux unix awk

我试图弄清一个氨基酸的首字母是否与其字母代码相同。

例如,甘氨酸以G开头,其字母代码也为(G) 另一方面,精氨酸以A开头,但字母代码为(R)

结果,我试图打印出具有相同字母代码和起始字母的氨基酸。

我有一个CSV数据文件,其中的列用','分隔

Name,One letter code,Three letter code,Hydropathy,Charge,Abundance,DNA codon(s)
Arginine,R,Arg,hydrophilic,+,0.0514,CGT-CGC-CGA-CGG-AGA-AGG
Asparagine,N,Asn,hydrophilic,N,0.0447,AAT-AAC
Aspartate,D,Asp,hydrophilic,-,0.0528,GAT-GAC
Glutamate,E,Glu,hydrophilic,-,0.0635,GAA-GAG
Glutamine,Q,Gln,hydrophilic,N,0.0399,CAA-CAG
Lysine,K,Lys,hydrophilic,+,0.0593,AAA-AAG
Serine,S,Ser,hydrophilic,N,0.0715,TCT-TCC-TCA-TCG-AGT-AGC
Threonine,T,Thr,hydrophilic,N,0.0569,ACT-ACC-ACA-ACG

我相信下面的代码是比较列的一种方法,但是我想知道如何从第一列中提取第一个字母并将其与第二列中的字母进行比较

awk '{ if ($1 == $2) { print $1; } }' < foo.txt

3 个答案:

答案 0 :(得分:3)

请您尝试以下。

awk 'BEGIN{FS=","} substr($1,1,1) == $2' Input_file

输出如下。

Serine,S,Ser,hydrophilic,N,0.0715,TCT-TCC-TCA-TCG-AGT-AGC
Threonine,T,Thr,hydrophilic,N,0.0569,ACT-ACC-ACA-ACG

说明: 添加上述代码的说明。

awk '                     ##Starting awk program here.
BEGIN{                    ##Starting BEGIN section for awk here.
 FS=","                   ##Setting FS as comma here, field separator.
}                         ##Closing BLOCK for BEGIN here.
substr($1,1,1) == $2      ##Using substr function of awk to get sub string from line, substr(line/variable/field, starting point, ending point) is method for using it. Getting 1st letter of $1 and comparing it with $2 of current line, if TRUE then it will print current line.
' Input_file              ##Mentioning Input_file name here.

答案 1 :(得分:2)

使用grep的简单方法:

$ grep -E '^(.)[^,]*,\1' input.csv 
Serine,S,Ser,hydrophilic,N,0.0715,TCT-TCC-TCA-TCG-AGT-AGC
Threonine,T,Thr,hydrophilic,N,0.0569,ACT-ACC-ACA-ACG

答案 2 :(得分:1)

与RavinderSingh的表达式相同,但字段选择器属性不同。

awk -F "," 'substr($1,1,1) == $2' InFile

Serine,S,Ser,hydrophilic,N,0.0715,TCT-TCC-TCA-TCG-AGT-AGC
Threonine,T,Thr,hydrophilic,N,0.0569,ACT-ACC-ACA-ACG