xargs -l 的替代品
我想将一堆目录从 DIR 重命名为 DIR.OLD。理想情况下,我会使用以下内容:
find . -maxdepth 1 -type d -name \"*.y\" -mtime +`expr 2 \* 365` -print0 | xargs -0 -r -I file mv file file.old
但是我想要执行此操作的计算机安装了 BusyBox,并且 BusyBox xargs 不支持“-I”选项。
收集文件数组然后在 shell 脚本中执行它们的常见替代方法有哪些?
I want to rename a bunch of dirs from DIR to DIR.OLD. Ideally I would use the following:
find . -maxdepth 1 -type d -name \"*.y\" -mtime +`expr 2 \* 365` -print0 | xargs -0 -r -I file mv file file.old
But the machine I want to execute this on has BusyBox installed and the BusyBox xargs doesn't support the "-I" option.
What are some common alternative methods for collecting an array of files and then executing on them in a shell script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
find
命令的-exec
和{}
功能,这样您就根本不需要任何管道:而且您也不需要需要指定“.”路径 - 这是
find
的默认值。并且您在"*.y"
中使用了额外的斜杠。当然,如果您的文件名实际上不包含引号。公平地说,应该指出的是,带有
while read
循环的版本是这里提出的最快的版本。以下是一些测量示例:我认为这是因为
find
和xargs
每次都会调用额外的 /bin/sh (实际上是exec(3)
执行此操作)执行命令的时间,而 shellwhile
循环则不然。更新:如果您的 busybox 版本是在没有
-exec
选项支持find
命令的情况下编译的,则while
循环或xargs
,在其他答案中建议(一个,两个),就是你的方式。You can use
-exec
and{}
features of thefind
command so you don't need any pipes at all:Also you don't need to specify '.' path - this is default for
find
. And you used extra slashes in"*.y"
. Of course if your file names do not really contain quotes.In fairness it should be noted, that version with
while read
loop is the fastest of proposed here. Here are some example measurements:I think it's because
find
andxargs
invokes additional /bin/sh (actuallyexec(3)
does it) every time for execute a command, while shellwhile
loop do not.Upd: If your busybox version was compiled without
-exec
option support for thefind
command then thewhile
loop orxargs
, suggested in the other answers (one, two), is your way.使用
for
循环。不幸的是,我认为 busybox 也不理解read -0
,因此您将无法正确处理换行符。如果您不需要,最简单的方法是:<前><代码>查找 . -maxdepth 1 -type d -name \"*.y\" -mtime +`expr 2 \* 365` -print |读取文件时; do mv -- "$file" "$file".old;完毕
使用
sh -c
作为命令。请注意,使用$0
来命名第一个参数(通常是脚本名称,并且转到$0
,当您使用- 抑制脚本时,这有点奇怪) c
,参数仍然转到$0
)并使用-n 1
来避免批处理。<前><代码>查找 . -maxdepth 1 -type d -name \"*.y\" -mtime +`expr 2 \* 365` -print0 | xargs -0 -r -n 1 sh -c 'mv -- "$0" "$0".old'
编辑 哎呀:我又忘记了
find -exec
。Use a
for
loop. Unfortunately I don't think busybox understandsread -0
either, so you won't be able to handle newlines properly. If you don't need to, it's easiest to just:Use a
sh -c
as the command. Note the slightly weird use of$0
to name the first argument (it would normally be the script name and that goes to$0
and while you are suppressing script with-c
, the argument still goes to$0
) and the use of-n 1
to avoid batching.Edit Oops: I forgot about the
find -exec
again.另一种方法是使用循环:
An alternative is to use a loop: