简体   繁体   中英

Merge files with same name in different folders

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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