文件内字符串部分唯一 - 仅保留第一个可用字符串

文件内字符串部分唯一 - 仅保留第一个可用字符串

我有一个名为的文件my_file.txt,其中包含以下字符串:

tasmax_day_ACCESS_historical_r1i1p1f3_gn.nc
tasmax_day_EC-Earth3_historical_r1i1p1f1_gn.nc
tasmax_day_EC-Earth3_historical_r1i1p1f1_gr.nc
tasmax_day_EC-Earth3_historical_r1i1p1f3_gn.nc
tasmax_day_HadGEM-MM_historical_r1i1p1f1_gn.nc
tasmax_day_HadGEM-MM_historical_r1i1p1f1_gr.nc
tasmax_day_HadGEM-MM_historical_r3i1p1f1_gn.nc
tasmax_day_MIROC_historical_r1i1p1f1_gn.nc
tasmax_day_MIROC_historical_r2i1p1f1_gn.nc

我需要执行一个以end 开头unique的子字符串,对于每个这样的子字符串,我只保留包含它的行(按字母顺序排列在前面)。tasmax_historical

我的预期输出my_file.txt如下:

tasmax_day_ACCESS_historical_r1i1p1f3_gn.nc
tasmax_day_EC-Earth3_historical_r1i1p1f1_gn.nc
tasmax_day_HadGEM-MM_historical_r1i1p1f1_gn.nc
tasmax_day_MIROC_historical_r1i1p1f1_gn.nc

谢谢你的帮助。

答案1

一个简单的 awk 就足够了。形成一个哈希映射,由唯一标识符字符串作为键并仅打印这些行

awk -F_ '{ key = $1 FS $2 FS $3 $4 } !unique[key]++ ' file

将分隔符设置为 时_,通过符号访问各个作品$1并形成直至包含的密钥$4。仅当该行(形成)的!unique[key]++键为不是已经看过。

假设你的tasmax字符串出现在$1historicalat 处$4,否则不起作用。


或者只是使用该工具,通过使用 fields进行定界sort来要求其唯一的 ( ) 行。适用于 BSD 和 GNU变体-u_1-4sort

sort -u -t_ -k1,4 < file

相关内容