递归重命名使用查找文件和sed [英] Recursively rename files using find and sed

查看:99
本文介绍了递归重命名使用查找文件和sed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一堆目录和重命名,在_test.rb结束_spec.rb结束,而不是所有文件。这件事情我从来没有相当想出如何使用bash这样做的这个时候,我以为我会放一些精力把它钉。我已经走了这么远了虽然短暂,但我最大的努力为:

I want to go through a bunch of directories and rename all files that end in _test.rb to end in _spec.rb instead. It's something I've never quite figured out how to do with bash so this time I thought I'd put some effort in to get it nailed. I've so far come up short though, my best effort is:

find spec -name "*_test.rb" -exec echo mv {} `echo {} | sed s/test/spec/` \;

NB:有Exec之后一个额外的回音使得命令打印,而不是运行,而我测试它

当我运行它的每一个匹配文件名中的输出是:

When I run it the output for each matched filename is:

mv original original

即。通过SED替代已丢失。有什么诀窍?

i.e. the substitution by sed has been lost. What's the trick?

推荐答案

这是因为 SED 接收字符串 {} 作为输入,如能与被验证

This happens because sed receives the string {} as input, as can be verified with:

find . -exec echo `echo "{}" | sed 's/./foo/g'` \;

这版画 foofoo 目录中的每个文件,递归。这样做的原因的行为是,当它扩大了整个命令流水线被执行一次,由外壳,

which prints foofoo for each file in the directory, recursively. The reason for this behavior is that the pipeline is executed once, by the shell, when it expands the entire command.

有没有引述 SED 管道以这样的方式,找到方式将执行它的每个文件,因为找到通过shell不执行命令,也没有管道或反引号的概念。在GNU的findutils手册介绍如何通过将管道在一个单独的shell脚本来执行类似的任务:

There is no way of quoting the sed pipeline in such a way that find will execute it for every file, since find doesn't execute commands via the shell and has no notion of pipelines or backquotes. The GNU findutils manual explains how to perform a similar task by putting the pipeline in a separate shell script:

#!/bin/sh
echo "$1" | sed 's/_test.rb$/_spec.rb/'

(有可能是使用 SH -c 和一吨的报价做到这一切在一个命令的一些不正当的方式,但我不会去尝试。 )

(There may be some perverse way of using sh -c and a ton of quotes to do all this in one command, but I'm not going to try.)

这篇关于递归重命名使用查找文件和sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆