Merging two files with same name

Hello all,

I have limited experience in shell scripting. Here goes my question:

I have two directories that have same number of files with same file names i.e. consider 2 directories A and B. Both directories have files 1.txt, 2.txt......

I need to merge the file 1.txt of A with file 1.txt of B, file 2.txt of A with file 2.txt of B, .....and so on.

Please suggest a UNIX script to do this.

Thanks.

One way, assuming A and B directories are in the current directory, and that A and B contain only files:

ls A | sed "s|.*|cat A/& >> B/&|" | sh
$ ls A
1.txt	2.txt	3.txt

$ cat A/1.txt
1

$ ls B
1.txt	2.txt	3.txt

$ cat B/1.txt
a

#... etc...

$ ls A | xargs -I{} cat A/{}
1
2
3

$ ls B | xargs -I{} cat B/{}
a
b
c

$ ls A | sed "s|.*|cat A/& >> B/&|" | sh

$ ls B | xargs -I{} cat B/{}            
a
1
b
2
c
3

Or probably simpler with a loop:

ls A | while read FILE; do
  cat A/"$FILE" >> B/"$FILE"
done

1 Like

Thanks scottn for the prompt reply.
The loop approach looks more elegant to me.
Just a small issue, what if I want the merging not to append to the directory B files, but rather put the results of merging in a separate file with the same file name?

As an example:

ls A | while read FILE; do
  cat A/"$FILE" B/"$FILE" >> C/"$FILE"
done

to append the A and B files to new files (with the same names) somewhere else.

1 Like

It will be better to add one judgment before attach file A to B. But this depends on the request

if [ -f "B/$FILE" ] ; then
  cat A/"$FILE" B/"$FILE" >> C/"$FILE"
fi

Thanks to both of you.

However, there's one thing to note here, unless the files end in a newline character the append will be at the end of the last line of the file and thus 2 lines will be in the same line