合并不同文件夹中具有相同名称的文件 [英] Merge files with same name in different folders
问题描述
我是Linux的新手,我正在寻找一个命令来合并具有相同名称但来自不同文件夹的文件.像这样:
I'm new to Linux and I'm looking for a command to merge files with the same name but from different folders. like this:
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中.
I want to merge two texts from folder 1 and subfolder 2, then put them into folder l1.
我知道了:
ls ./1 | while read FILE; do
cat ./1/"$FILE" ./1/2/"$FILE" >> ./l1/"$FILE"
done
这个似乎很好用,两个文件被合并,但是,在文件夹l1中创建了一个新的空文件2,并在shell上显示了两个警告消息:cat:./1/2:是目录cat:./1/2/2:没有这样的文件或目录
This one seems working well, two files are merged, however, a new empty file 2 is created in folder l1, and two pieces warning message on shell: cat: ./1/2: Is a directory cat: ./1/2/2: No such file or directory
我想知道有关新文件2和警告消息的说明,更重要的是如何改进命令行或新解决方案,因为我有数十个文件夹1.
I want to know explanations for new file 2 and warning message, more important how to improve the command line or new solutions because I have dozens of folder 1.
推荐答案
您的代码看起来还不错.它发出警告是因为您也尝试合并目录!您可以添加检查以跳过目录,如下面的代码:
Your code looks quite OK. It is giving warnings because you are trying to merge directories as well! You can add a check to skip over directories, like the code below:
#!/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
引用上面的变量很重要,以防止单词拆分.
It's important to quote the variables above to prevent word splitting.
这篇关于合并不同文件夹中具有相同名称的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!