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