bash 不同文件夹中的同名文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17281045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
files with same name in different folders
提问by Bioinfoguy
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
Acontains files1.txt,2.txt,3.txt, … - folder
Bcontains files1.txt,2.txt,3.txt, …
- 文件夹
A包含文件1.txt,2.txt,3.txt, ... - 文件夹
B包含文件1.txt,2.txt,3.txt, ...
I would like to concatenate the two files A/1.txtand B/1.txt, and A/2.txtand B/2.txt, …
我想连接两个文件A/1.txtand B/1.txt, and A/2.txtand B/2.txt, ...
I'm looking for a shell command to do that:
我正在寻找一个 shell 命令来做到这一点:
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 Aand B, if only names are matched.
对于文件夹A和 中的所有文件B,如果只有名称匹配。
回答by simonzack
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
回答by jm666
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 catwith the above arguments... or,
将cat使用上述参数运行...或者,
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...
等等...

