【问题标题】:Merge multiple files containing same IDs - Linux合并包含相同 ID 的多个文件 - Linux
【发布时间】:2019-07-31 11:46:00
【问题描述】:

我在一个文件夹中有 10000 个文件,如下所示:

  • 1000.htm
  • Page_1000.html
  • file-1000.txt
  • 2000.htm
  • Page_2000.html
  • file-2000.txt

我想合并每个名称相似的文件

example :
1000.htm Page_1000.html file-1000.txt > 1.txt
2000.htm Page_2000.html file-2000.txt > 2.txt

我曾尝试像这样使用 cat 进行合并,但我无法在 10k 文件中执行此操作。

cat 1000* > 1.txt 
cat 2000* > 2.txt 

谢谢

【问题讨论】:

    标签: search awk merge grep cat


    【解决方案1】:

    您可能无法这样做,因为通配符 (*) 试图扩展到过多的参数。您可以使用 find 来查找与模式匹配的所有文件,然后使用 xargs 对它们执行 cat 。

    find . -name '1000*' -print0 | xargs -0 cat > 1.txt
    

    '-print0' 和 '-0' 将分隔空 (\0) 字符而不是默认的换行符 (\n)。这样,文件名中带有换行符的文件也可以按预期工作。

    【讨论】:

      【解决方案2】:
      find . -name '*.htm' -printf '%P\n' |
      while IFS='.' read -r key sfx; do
          cnt=$(( cnt + 1 ))
          cat "${key}.htm" "Page_${key}.html" "file-${key}.txt" > "${cnt}.txt"
      done
      

      虽然您应该考虑在输出文件名中使用键而不是 cnt 变量,这样很容易判断输出文件中包含哪些输入文件。

      【讨论】:

        【解决方案3】:
        i=1;
        for ((num = 1000; num < 10000; num+=1000));
        do 
        cat ${num}.htm Page_${num}.html file-${num}.txt > ${i}.txt
        i=$((i + 1));
        done
        

        您可以根据需要更改 num

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-29
          • 2019-10-02
          • 2014-12-23
          • 1970-01-01
          • 2023-03-08
          • 2013-01-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多