提问人:Shafaque Zahra 提问时间:10/20/2023 更新时间:10/21/2023 访问量:95
按匹配其他文件的顺序打印行 [已关闭]
print rows by matching order from other file [closed]
问:
文件1.txt
SRR1071717
SRR1079830
SRR1081765
SRR1085402
SRR1086236
SRR1092208
SRR1093930
SRR1097296
SRR1099957
SRR1120296
文件2.txt
SRR1120296,female
SRR1099957,male
SRR1097296,female
SRR1093930,female
SRR1092208,female
SRR1086236,female
SRR1085402,male
SRR1081765,male
SRR1079830,male
SRR1071717,male
期望输出
SRR1071717 male
SRR1079830 male
SRR1081765 male
SRR1085402 male
SRR1086236 female
SRR1092208 female
SRR1093930 female
SRR1097296 female
SRR1099957 male
SRR1120296 female
我想保持 file1.txt 的顺序来打印 file2.txt。两个文件的行数相等(不能使用排序,因为顺序会改变)。
答:
-1赞
pmf
10/20/2023
#1
您可以将 中的行存储到数组中,然后使用 中的索引打印它们。 是您正在读取第一个文件的条件(即 ,请注意参数的顺序)。file2.txt
file1.txt
NR==FNR
file2.txt
awk -F, '{if (NR==FNR) a[$1]=$0; else print a[$1]}' file2.txt file1.txt
SRR1071717,male
SRR1079830,male
SRR1081765,male
SRR1085402,male
SRR1086236,female
SRR1092208,female
SRR1093930,female
SRR1097296,female
SRR1099957,male
SRR1120296,female
1赞
stuffy
10/20/2023
#2
也许试试
awk -v FS="," 'FNR==NR {a[$1]=$2; next}; {if ($1 in a) print $1,a[$1]}' file2.txt file1.txt
FNR==NR 表示第一个文件
a[$1]=$2 就像 a[SRR1120296]=女性
第二个文件SRR1120296如果是数组 A 中的索引,则打印SRR1120296和数组值
评论
0赞
Ed Morton
10/28/2023
无需if
- 'FNR==NR {a[$1]=$2; next} $1 in a{print $1,a[$1]}'
评论