Files with same names in different folders

Hello,

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

If I would like to concatenate the two files /A/1.txt and /B/1.txt and A/2.txt and B/2.txt, what is a shell command that I had to do to do that:

If file name in A is equal the file name in B; cat /A/1.txt /B/1.txt; done

I would like to do that for all files in folders A and B, if only names are matched.

Thank you in advance,
Regards,
Mohamed

The location of the concatenated file directory is $DEST. You choose that.
The name of the newly concatenated file will be [oldfilename].cat

ls /A/*.txt >/tmp/A.lis
ls /B/*.txt >/tmp/B.lis
awk 'FILENAME=="/tmp/A.lis" {arr[$0]++}
       FILENAME=="/tmp/B.lis"  { if ($0 in arr){ print $0} ' /tmp/A.lis /tmp/B.lis > /tmp/list
while read fname 
do
    cat /A/${fname} /B/${fname} > $DEST/${fname}.cat
done < /tmp/list

There are other shorter pieces of code that can do this but you can see what this one is doing easily. So you can edit it to make minor changes.

try without creating list files ...

cd /A
for file in *.txt
do
    [ -f ../B/$file ] && (cat $file ../B/$file > /dir/${file}.cat)
done

The latter with && safety and " " safety and without ( )

cd /A &&
for file in *.txt
do
  [ -f ../B/"$file" ] &&
   cat "$file" ../B/"$file" > /dir/"$file".cat
done
2 Likes

i can see that " [ -f ../B/"$file" ] && " may be useful ...

i am unclear, however, on the usefulness of " cd /A && " since the o/p owns the directory and knows it exists as well as is making it the reference directory ... adding the " && " after the cd seems to be just an unnecessary check ...

1 Like

Just a good habit. In

cd dir &&
rm *

with the extra && you can stay cool seeing "not found", "not a directory", "permission denied".

1 Like

i am all for good habits and i am also for efficient coding which by the way are not mutually exclusive ... however, putting in unnecessary checks in code that is not standard coding practice -- as well-meaning as it is -- does not help readability and increases the possibility of confusion ...

otherwise coding will be ...

#! /bin/ksh

cd /dir &&
pwd &&
ls -l &&
cd /otherdir &&
pwd &&
ls -l &&
date +%Y%m%d &&
hostname &&

exit 0
1 Like