通过 exec 对 find 的输出进行 Bash 变量替换 [英] Bash variable substitution on find's output through exec

查看:11
本文介绍了通过 exec 对 find 的输出进行 Bash 变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 find 的输出上应用 bash 变量替换?我知道我已经看到有人在堆栈溢出时这样做了,但我似乎再也找不到那个特定的帖子了.

Is there any way to apply bash variable substitution on find's output? I know I've seen some one do it on stack overflow but I can't seem to find that particular post anymore.

作为示例,假设我想将文件 *.png 重命名为 *_copy.png.我知道我可以使用 rename 来做到这一点,但这只是一个思想实验.

As an example, let's say I want to rename files *.png to *_copy.png. I know I can do this using rename but it's just a thought experiment.

现在我希望能够做这样的事情:

Now I'd like to be able to do something like this:

find . -name "*png" -exec mv "{}" "${{}%.*}_copy.png" ;

这会导致无效替换.当然,我可以先将输出分配给一个变量,然后在子 shell 中应用替换,但是这真的是唯一的方法吗?

Which results in an invalid substitution. Of course, I could first assign the output to a variable and then apply substitution in a sub-shell, but is this really the only way?

find . -name "*.png" -exec bash -c 'var="{}";  mv "{}" "${var%.*}_copy.png"' ;

或者有什么方法可以直接从{}实现?

Or is there any way this can be achieved directly from {}?

共识

正如 Etan Reisner 所说,处理 find 输出的更好、更安全的方法是将其作为位置参数传递.

As Etan Reisner remarked, a better and safer way to handle the output of find would be to pass it as positional argument.

find . -name "*.png" -exec bash -c 'mv "$0" "${0%.*}_copy.png"' "{}" ;

推荐答案

我花了一段时间才得到这个问题.基本上你问的是:

It took me a while to get the question. Basically you are asking if something like:

echo "${test.png%.png}"

可以用来获取单词test.

答案是否定的.以 ${ 开头的 字符串操作运算符参数替换运算符的子集.它们仅适用于变量,而不适用于字符串文字,这意味着您需要先将字符串存储在变量中.像这样:

The answer is no. The string manipulation operators starting with ${ are a subset of the parameter substitution operators. They work only on variables, not with string literals, meaning you need to store the string in a variable before. Like this:

img="test.png"
echo "${img%.png}"

<小时>

仅针对来自 Google 的旅行者,我会使用 rename 来完成此特定任务.(正如他的问题中已经提到的OP).该命令可能如下所示:


Just for travellers from Google, I would use rename for this particular task. (As the OP already mentioned in his question). The command could look like this:

find -name '*png' -execdir rename 's/.png/_copy.png/' {} +

这篇关于通过 exec 对 find 的输出进行 Bash 变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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