Merge files with same name in different folders

一曲冷凌霜 提交于 2021-01-29 04:34:02

问题


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, ...

I want to merge two texts from folder 1 and subfolder 2, then put them into folder l1.

I got this:

    ls ./1 | while read FILE; do

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

    done

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

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.


回答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.



来源:https://stackoverflow.com/questions/41864322/merge-files-with-same-name-in-different-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!