[英]Concatenate files content into one single file based on their name in 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
以下內容可確保不會同時打開太多文件句柄。 PATHNAMES應該替換為適當的表達式,以產生要處理的文件的路徑名。
警告:如果更改了先前存在的文件,則不會給出任何警告。
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
嘗試這個 :
for f in *.*; do
cat "${f}" >> "${f%.*}"
done
當前目錄中所有帶點的文件都會被處理。
如果僅當第一部分匹配多個文件時才要生成新文件:
files=(*)
for f in *.*; do
numf=$(grep -o "${f%.*}" <<< "${files[*]}" | wc -l)
[ $numf -gt 1 ] && cat "${f}" >> "${f%.*}"
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.