あるファイルの列が別のファイルの列と部分的に一致する場合は、一致してから2つのファイルの列を印刷します。

あるファイルの列が別のファイルの列と部分的に一致する場合は、一致してから2つのファイルの列を印刷します。

フィールドがカンマで区切られた2つのファイルがあります。

aks@dev1:~$ cat dir.txt

/home/aks/cleanup,512

/home/aks/git,208

/home/aks/github,424


/home/aks/predirsize,216

/home/aks/sample,288004
aks@dev1:~$ cat config.txt

/home/aks/cleanup,1,7,2

/home/aks/sample/aks,1,2,1

/home/vbht/test_bkup,1,7,None

config.txtの最初のフィールドでdir.txtの最初のフィールドを見つける必要があり、完全にまたは部分的に一致する場合は、config.txtの最初のフィールド、dir.txtの2番目のフィールド、dir 2番目、3番目、.txtの4番目のフィールドは.txtを構成します。

予想出力 -

/home/aks/cleanup,512,1,7,2

/home/aks/sample/aks,288004,1,2,1

ベストアンサー1

方法は次のとおりですawk

$ awk -F, -v OFS=, '{ if(/^$/){next} if(NR==FNR){f1[$1]=$2;} else{for(path in f1){ if($1 ~ path ){print $1,f1[path],$2,$3,$4}}}}' dir.txt config.txt 
/home/aks/cleanup,512,1,7,2
/home/aks/sample/aks,288004,1,2,1

これは複数行に分けて説明するのと同じです。この内容を端末に直接コピーして貼り付けることができます。

awk -F, -v OFS=, '
 { 
    ## Skip empty lines
    if(/^$/){ next } 

    ## If this is the first file, store the first field 
    ## as a key and the second field as its value in the 
    ##associative array f1 
    if(NR==FNR){ f1[$1]=$2 } 

    ## If this is the second file
    else{
        ## for each of the keys in f1, the paths
        for(path in f1){ 
            ## If the 1st field of this line matches a path
            if($1 ~ path){
                ## print all the things
                print $1,f1[path],$2,$3,$4
            }
        }
    }
 }' dir.txt config.txt 

おすすめ記事