(FYI, I have very little shell scripting knowledge)

I have a ton of files and directories that look something like


I would like to be able to combine/concat all the files with the same file names together, and then put everything in the root. So the end result would look like

-root/a.txt (combined from dir1 and dir2)
-root/b.txt (combined from dir3 and dir4)

If that's not possible, I'd even settle for moving all the files to the root, and doing a batch rename. So something like


Hope that makes sense, and thanks in advance :)


If want to combine them and the file names are known beforehand then you could try something like:

for i in a b c d
find <root direcoty> -iname "$i.txt" -exec cat {} \; > <root directory>/$i.txt

For each a, b, c, and d we look for the files that have the name a.txt (b.txt ... d.txt) in all the directories and invoke cat on the file names and pipe the output to one file with the same name under the root directory.

If they are not known beforehand, it gets a little bit tricky, but here:

for i in `find <root directory> -type f | sed -E 's!\./.*/([a-zA-Z0-9]+)\.txt!\1!g'`
find <root directory> -iname "$i.txt" -exec cat {} \; > <root directory>/$i.txt

It's the same as the command before, except from where we get our list. We first get a list of all the files in the root directory then remove all parts of the file names to only include the, eh, file name (no direcotry and no extension). You should note that this will only work for files that have lower and upper case letters mixed with numbers as their names, no dashes or under scrolls. If you want them then change [a-zA-Z0-9] to [a-zA-Z0-9-_].

Change any instance of <root directory> to the desired path.

  • awesome! that did exactly what i wanted :) thanks a million – Kar Jan 19 '12 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.