Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

(FYI, I have very little shell scripting knowledge)

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

-root
 -dir1/a.txt
 -dir2/a.txt
 -dir3/b.txt
 -dir4/b.txt
 -dir5/c.txt

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)
-root/c.txt

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

-root/a.txt.1
-root/a.txt.2
-root/b.txt.1
-root/b.txt.2
-root/c.txt.1

Hope that makes sense, and thanks in advance :)

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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
do
find <root direcoty> -iname "$i.txt" -exec cat {} \; > <root directory>/$i.txt
done

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'`
do
find <root directory> -iname "$i.txt" -exec cat {} \; > <root directory>/$i.txt
done

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.

share|improve this answer
    
awesome! that did exactly what i wanted :) thanks a million –  Kar Jan 19 '12 at 21:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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