简体   繁体   English

根据Linux中文件名将文件内容合并为一个文件

[英]Concatenate files content into one single file based on their name in linux

I want to concatenate files into one single file when the first part of their name match for example if I have the following files: 我想在文件名的第一部分匹配时将文件串联为一个文件,例如,如果我有以下文件:

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

the result would be like 结果就像

file1 will contain 
this is file1
this is file2
file2 will contain
this is file1
this is file2

The following ensures that not too many file handles are open at the same time. 以下内容可确保不会同时打开太多文件句柄。 PATHNAMES should be replaced by an appropriate expression yielding the path names of the files to be processed. PATHNAMES应该替换为适当的表达式,以产生要处理的文件的路径名。

WARNING: No warning is given if a pre-existing file is altered. 警告:如果更改了先前存在的文件,则不会给出任何警告。

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

Try this : 尝试这个 :

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

All files with a dot in current dir are processed. 当前目录中所有带点的文件都会被处理。

If you want to generate new file only if first part match multiple files : 如果仅当第一部分匹配多个文件时才要生成新文件:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM