2016-03-18 21 views
0

我想連接文件合併成一個單一的文件時,他們的名字匹配,例如第一部分,如果我有以下文件:連接文件的內容到一個單一的文件基礎上他們的名字在linux

file1.name1 which contains : 
this is file1 

file1.name2 which contains : 
this is file2 

file2.name3 which contains : 
this is file1 

file2.name4 which contains : 
this is file2 

的結果會像

file1 will contain 
this is file1 
this is file2 
file2 will contain 
this is file1 
this is file2 
+0

您是否嘗試過這個事情。如果你環顧這個網站,有許多答案與使用'awk'(例如)做這種事情有關。 –

回答

1

試試這個。

如果你想生成只有第一部分匹配多個文件新文件:

files=(*) 
for f in *.*; do 
    numf=$(grep -o "${f%.*}" <<< "${files[*]}" | wc -l) 
    [ $numf -gt 1 ] && cat "${f}" >> "${f%.*}" 
done 
2

以下內容確保不會同時打開太多的文件句柄。 PATHNAMES應替換爲適當的表達式,產生要處理的文件的路徑名。

警告:如果預先存在的文件被更改,則不會發出警告。用在當前目錄進行處理

for f in *.*; do 
    cat "${f}" >> "${f%.*}" 
done 

所有文件:

awk -v maxhandles=10 ' 
    { nparts=split(FILENAME,a,"."); 
    # if FILENAME does not match the pattern: 
    if (nparts <= 1) { print; next } 
    # n is the number of open handles: 
    if (! (a[1] in handles)) { 
     n++; 
     if (n > maxhandles) { 
     for (i in handles) { close(i) }; 
     n=0; 
     delete handles; 
     } 
    } 
    handles[a[1]]; 
    print >> a[1] 
    } 
' PATHNAMES 
相關問題