简体   繁体   中英

files with same name in different folders

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.

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

For simple things maybe will be enough the next syntax:

cat ./**/1.txt 

or you can simply write

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

eg

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM