在Linux命令行中复制多个子目录中的文件
假设我有以下子目录
./a/, ./b/, ./c/, ...
,也就是说,在我当前的工作目录中有这些子目录 a/
、b/
和 c/
,并且在每个子目录都是文件。在目录a/
中是文件a.in
,在目录b/
中是文件b.in
并且等等。
我现在想将每个 .in
文件复制到 .out
文件,即 a.in
到 a.out< /code> 和
b.in
到 b.out
,我希望它们位于从中复制的目录中。所以a.out
将在目录a/
中找到。
我尝试了各种不同的方法,例如
find ./ -name '*.in'|cp * *.out
它不起作用,因为它认为 *.out
是一个目录。也尝试过,
ls -d */ | cd; cp *.in *.out
但它会列出子目录,进入每个子目录,但不会让 cp 完成它的工作(仍然不起作用)
该
find ./ -name '*.in'
命令工作正常。有没有办法将参数传递给赋值运算符?例如
find ./ -name '*.in'| assign filename=|cp filename filename.out
,其中 assign filename=
为 filename 提供每个 .in
文件的值。事实上,如果赋值可以去掉 .in
文件扩展名,那就更好了,这样我们就不会得到 a.in.out
我们会得到首选的 < code>a.out
感谢您的宝贵时间。
Let's say I have the following subdirectories
./a/, ./b/, ./c/, ...
That is, in my current working directory are these subdirectories a/
, b/
and c/
, and in each of these subdirectories are files. In directory a/
is the file a.in
, in directory b/
is the file b.in
and so forth.
I now want to copy each .in
file to a .out
file, that is, a.in
to a.out
and b.in
to b.out
, and I want them to reside in the directories they were copied from. So a.out
will be found in directory a/
.
I've tried various different approaches, such as
find ./ -name '*.in'|cp * *.out
which doesn't work because it thinks *.out
is a directory. Also tried
ls -d */ | cd; cp *.in *.out
but it that would list the subdirectories, go into each one of them, but won't let cp
do it's work (which still doesn't work)
The
find ./ -name '*.in'
command works fine. Is there a way to pipe arguments to an assignment operator? E.g.
find ./ -name '*.in'| assign filename=|cp filename filename.out
where assign filename=
gives filename the value of each .in
file. In fact, it would be even better if the assignment could get rid of the .in
file extension, then instead of getting a.in.out
we would get the preferred a.out
Thank you for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让 shell 帮助你:
我刚刚使用了你所说的 find 命令,让 bash 一次读取一个文件名的输出。因此,bash while 循环一次获取一个文件名,进行一点替换,然后直接复制。又好又简单(但未经测试!)。
Let the shell help you out:
I just took the find command you said works and let bash read its output one filename at a time. So the bash while loop gets the filenames one at a time, does a little substitution, and a straight copy. Nice and easy (but not tested!).
尝试使用 for 循环:
glob 应该捕获下一个目录中具有 .in 扩展名的所有文件。在 cp 命令中,它会去掉 .in 后缀,然后附加 .out (请参阅 Bash 中的变量重整字符串运算符)
或者,如果您想递归到每个子目录(不仅仅是 1 层深度),请将 glob 替换为 find:
Try a for loop:
The glob should catch all the files one directory down that have a .in extension. In the cp command, it strips off the .in suffix and then appends a .out (see Variable Mangling in Bash with String Operators)
Alternatively, if you want to recurse into every subdirectory (not just 1 level deep) replace the glob with a find:
这应该可以解决问题!
This should do the trick!