4

I am looking for a command line that can do some operations on two files that have the same names but in different folders.

for example if

  • folder A contains files 1.txt, 2.txt, 3.txt, …
  • folder B contains files 1.txt, 2.txt, 3.txt, …

I would like to concatenate the two files A/1.txt and B/1.txt, and A/2.txt and B/2.txt, …

I'm looking for a shell command to do that:

if file name in A is equal the file name in B then: 
    cat A/1.txt B/1.txt
end if

for all files in folders A and B, if only names are matched.

1
  • Where do you want the output of the cat to go? Your example goes to stdout but I wasn't sure if that's your intention. Or do you have a 3rd file for each pair? Commented Jun 24, 2013 at 17:08

3 Answers 3

6

Try this to get the files which have names in common:

cd dir1
find . -type f | sort > /tmp/dir1.txt
cd dir2
find . -type f | sort > /tmp/dir2.txt
comm -12 /tmp/dir1.txt /tmp/dir2.txt

Then use a loop to do whatever you need:

for filename in "$(comm -12 /tmp/dir1.txt /tmp/dir2.txt)"; do
    cat "dir1/$filename"
    cat "dir2/$filename"
done
Sign up to request clarification or add additional context in comments.

1 Comment

You hardly need the temporary files or comm. Just loop over files in dir1 and skip the ones which are not also in dir2.
6

For simple things maybe will be enough the next syntax:

cat ./**/1.txt 

or you can simply write

cat ./{A,B,C}/1.txt

e.g.

$ mkdir -p A C B/BB
$ touch ./{A,B,B/BB,C}/1.txt
$ touch ./{A,B,C}/2.txt

gives

./A/1.txt
./A/2.txt
./B/1.txt
./B/2.txt
./B/BB/1.txt
./C/1.txt
./C/2.txt

and

echo ./**/1.txt

returns

./A/1.txt ./B/1.txt ./B/BB/1.txt ./C/1.txt

so

cat ./**/1.txt

will run the cat with the above arguments... or,

echo ./{A,B,C}/1.txt

will print

./A/1.txt ./B/1.txt ./C/1.txt #now, without the B/BB/1.txt

and so on...

Comments

4

Will loop through all files in folder A, and if a file in B with same name exists, will cat both:

for fA in A/*; do
    fB=B/${f##*/}
    [[ -f $fA && -f $fB ]] && cat "$fA" "$fB"
done

Pure , except the cat part, of course.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.