bash 如何在 find 命令中使用变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32142285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use a variable in find command?
提问by nicusska
I am totally new in bash so sorry if my question is not well formatted or does not make sense :)
我是 bash 新手,如果我的问题格式不正确或没有意义,我很抱歉:)
I'm trying to do something like that:
我正在尝试做这样的事情:
#..................... previous code where F is defining
filename="$F";
echo "$filename";
find . -name ????? | while read fname; do
echo "$fname";
done;
I want to use my variable $filename in find command (instead of ????), but I don't know how. I add some fixed value there for testing purpose, for example "abc.txt" (which exists and is stored in my variable), it works well, I just don't know how to use variable in find command.
我想在 find 命令中使用我的变量 $filename(而不是 ????),但我不知道如何。我在那里添加了一些固定值用于测试目的,例如“abc.txt”(存在并存储在我的变量中),它运行良好,我只是不知道如何在 find 命令中使用变量。
Something like
就像是
find . -name '$filename.txt' | while read fname;
UPDATE: (I have 2 files (.xml and .txt) with the same name in folder)
更新:(我在文件夹中有 2 个同名文件(.xml 和 .txt))
find . -type f -name \*.xml | while read F;
do something || echo $F;
cat "$F";
#name without extenssion
filename="${F%.*}";
echo "$filename";
find . -name "$filename.txt" | while read fname; do
echo "$fname";
done;
done;
采纳答案by ryanpcmcquen
This will work:
这将起作用:
filename="$F";
echo "$filename";
find . -name "$filename.txt" | while read fname; do
echo "$fname";
done;
Although you could just as easily do:
虽然你可以很容易地做到:
find . -name "$F.txt" | while read fname; do
echo "$fname";
done;
Double quotes (or no quotes at all) are necessary for variable expansion. Single quotes will not work.
变量扩展需要双引号(或根本没有引号)。单引号不起作用。