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

问题描述

有没有办法在 find 的输出上应用 bash 变量替换?我知道我已经看到有人在堆栈溢出,但我似乎无法找到特定的职位了。



作为一个例子,假设我想重命名文件 *。png * _ copy.png 。我知道我可以使用 rename 来做到这一点,但这只是一个想法实验。



现在我想成为能够做到这样的事情:

  find。 -name* png-exec mv{}$ {{}%。*} _ copy.png\; 

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

  find。 -name* .png-exec bash -c'var ={}; mv{}$ {var%。*} _ copy.png'\; 

是否有任何方法可以直接从 { }



共识

Etan Reisner 指出,处理find输出的更好更安全的方法是将其作为位置参数传递。

 查找。 -name* .png-exec bash -cmv$ 0$ {0%。*} _ copy.png'{}\; 


解决方案

我花了一段时间才得到问题。基本上你是问如果是这样的:
$ b $ pre $ echo$ {test.png%.png}

code>

可以用于获取单词 test



答案是否定的。以 $ {开头的, / code>是参数替换运算符。它们只能用于变量,而不能用于字符串,这意味着您需要将字符串存储在变量中。像这样:

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






只为Google的游客,我会用重命名为这个特定的任务。 (正如OP在他的问题中已经提到的那样)。命令可能如下所示:

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


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.

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" \;

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 {}?

Consensus

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}"

could be used to get the word 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}"


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/' {} +

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

07-23 15:40
查看更多