繁体   English   中英

合并不同文件夹中的同名文件

[英]Merge files with same name in different folders

我是 Linux 新手,我正在寻找一个命令来合并具有相同名称但来自不同文件夹的文件。 像这样:

folder 1, folder l1

folder 1 contains folder 2 and files 1.txt, 2.txt, 3.txt, ... 

folder 2 contains files 1.txt, 2.txt, 3.txt, ...

我想合并文件夹 1 和子文件夹 2 中的两个文本,然后将它们放入文件夹 l1。

我懂了:

    ls ./1 | while read FILE; do

        cat ./1/"$FILE" ./1/2/"$FILE" >> ./l1/"$FILE"

    done

这个似乎运行良好,合并了两个文件,但是,在文件夹 l1 中创建了一个新的空文件 2,并在 shell 上创建了两条警告消息: cat: ./1/2: Is a directory cat: ./1/2 /2: 没有那个文件或目录

我想知道新文件 2 和警告消息的解释,更重要的是如何改进命令行或新解决方案,因为我有几十个文件夹 1。

你的代码看起来很不错。 它发出警告,因为您也在尝试合并目录! 您可以添加检查以跳过目录,如下面的代码:

#!/bin/bash

cd 'folder 1'
for file in *.txt; do
  [[ ! -f $file ]] && continue      # pick up only regular files

  otherfile="folder 2/$file"
  [[ ! -f $otherfile ]] && continue # skip if there is no matching file in folder 2
  cat "$file" "$otherfile" > "folder l1/$file.merged"
done

引用上述变量以防止分很重要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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