0

I want to write a shell script to merge contents of multiple files in a given directories.

DIR1 contains sample1.txt sample2.txt
    sample1.txt contents  :---this is sample1 file---
    sample2.txt contents  :---this is sample2 file---

DIR2 contains demo1.txt demo2.txt
    demo1.txt contents  :---this is demo1 file---

I tried the solution :

(find /home/DIR1  /home/DIR2 -type f | xargs -i cat {} ) > /result/final.txt

I got the output as well but sequence of file has changed.

this is sample2 file---  this is sample1 file---  this is demo1 file---

I need every file's output ina different line . how to do this? Is there any way to maintain the order of files output like If i want to place particular file's output at the top or so? and what is the use of " xargs -i " option in the cmd?

Thanks.

1
  • Which files you're trying to merge?
    – kenorb
    May 28, 2015 at 13:25

2 Answers 2

1

You can use this:

(find directory -type f | xargs -i cat {} ) > TOTAL

Looks for all files in directory and puts all content in TOTAL.

4
  • I need to merge contents in a given file's order what should I add to the above cmd?
    – user
    May 29, 2015 at 6:10
  • Please, add an example about this, because it is not clear what you expect. May 29, 2015 at 6:33
  • I have modified the above code please check
    – user
    May 29, 2015 at 12:34
  • above command worked but it doesn't add new file's contents to new line how to acheive the same?
    – user
    Jun 22, 2015 at 12:27
2

You need to go directly into that directory:

cat /home/me/mydir/* > /home/me/finalData.txt
3
  • No i can't i am writitng shell script
    – user
    May 28, 2015 at 13:21
  • @ashwini What do you mean? Can you share your script then?
    – kenorb
    May 28, 2015 at 13:25
  • I have to write a shell script which will run from different [base]location other than /home/me/mydir/ location.
    – user
    May 29, 2015 at 4:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .