不同文件夹中具有相同名称的文件

Bio*_*guy 4 linux bash shell scripting file

我正在寻找一个命令行,可以对两个具有相同名称但在不同文件夹中的文件执行某些操作.

例如,如果

  • 文件夹中A包含的文件1.txt,2.txt,3.txt,...
  • 文件夹中B包含的文件1.txt,2.txt,3.txt,...

我想将两者连接起来的文件A/1.txtB/1.txt,和A/2.txtB/2.txt,...

我正在寻找一个shell命令来做到这一点:

if file name in A is equal the file name in B then: 
    cat A/1.txt B/1.txt
end if
Run Code Online (Sandbox Code Playgroud)

在文件夹中的所有文件AB,如果只有名称匹配.

sim*_*ack 5

尝试执行以下操作以获取具有相同名称的文件:

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
Run Code Online (Sandbox Code Playgroud)

然后使用循环执行所需的任何操作:

for filename in "$(comm -12 /tmp/dir1.txt /tmp/dir2.txt)"; do
    cat "dir1/$filename"
    cat "dir2/$filename"
done
Run Code Online (Sandbox Code Playgroud)


jm6*_*666 5

对于简单的事情,下一个语法可能就足够了:

cat ./**/1.txt 
Run Code Online (Sandbox Code Playgroud)

或者你可以简单地写

cat ./{A,B,C}/1.txt
Run Code Online (Sandbox Code Playgroud)

例如

$ mkdir -p A C B/BB
$ touch ./{A,B,B/BB,C}/1.txt
$ touch ./{A,B,C}/2.txt
Run Code Online (Sandbox Code Playgroud)

./A/1.txt
./A/2.txt
./B/1.txt
./B/2.txt
./B/BB/1.txt
./C/1.txt
./C/2.txt
Run Code Online (Sandbox Code Playgroud)

echo ./**/1.txt
Run Code Online (Sandbox Code Playgroud)

回报

./A/1.txt ./B/1.txt ./B/BB/1.txt ./C/1.txt
Run Code Online (Sandbox Code Playgroud)

所以

cat ./**/1.txt
Run Code Online (Sandbox Code Playgroud)

cat使用上述参数运行...或者,

echo ./{A,B,C}/1.txt
Run Code Online (Sandbox Code Playgroud)

将打印

./A/1.txt ./B/1.txt ./C/1.txt #now, without the B/BB/1.txt
Run Code Online (Sandbox Code Playgroud)

等等...