文件內字串部分唯一 - 僅保留第一個可用字串

文件內字串部分唯一 - 僅保留第一個可用字串

我有一個名為的文件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

相關內容