查找文件名是否包含 bash 脚本中的某个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50321291/
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
find if filename contains a certain string in bash script
提问by katiayx
I have a bunch of output files in a directory, such as: a.out, b.out c.out, etc.
我在一个目录中有一堆输出文件,例如:a.out、b.out c.out 等。
I want to search through the output files and if the output file namecontains a certain string (such as "a"), then it will print the corresponding output file "a.out" to screen.
我想搜索输出文件,如果输出文件名包含某个字符串(例如“a”),那么它会将相应的输出文件“a.out”打印到屏幕上。
After I cd-ed into the output files directory, here's my code:
在我 cd 进入输出文件目录后,这是我的代码:
OUT_FILE="*.out"
OT=$OUT_FILE
STRING="a"
For file in "$OT";do
if [[$file == *"$STRING"*]];then
echo $file
fi
done
The error I received is [[*.out: command not found. It looks like $file is interpreted as $OT, not as individual files that matches $OT.
我收到的错误是 [[*.out: command not found。看起来 $file 被解释为 $OT,而不是与 $OT 匹配的单个文件。
But when I removed the if statement and just did a for-loop to echo each $file, the output gave me all the files that ended with .out.
但是当我删除 if 语句并只执行 for 循环来回显每个 $file 时,输出给了我所有以 .out 结尾的文件。
Would love some help to understand what I did wrong. Thanks in advance.
希望得到一些帮助以了解我做错了什么。提前致谢。
回答by Jens
Without bashisms like [[
(works in any Bourne-heritage shell) and blindingly fast since it does not fork any utility program:
没有像[[
(适用于任何 Bourne-heritage shell)之类的 bashisms并且非常快,因为它没有分叉任何实用程序:
for file in *.out; do
case $file in
(*a*) printf '%s\n' "$file";;
esac
done
If you want you can replace (*a*)
with (*$STRING*)
.
如果你愿意,你可以(*a*)
用(*$STRING*)
.
Alternative if you have a find
that understands -maxdepth 1
:
如果你有一个find
理解的替代方案-maxdepth 1
:
find . -maxdepth 1 -name \*"$STRING"\*.out
PS: Your question is a bit unclear. The code you posted tests for a
in the file name(and so does my code). But your text suggests you want to search for a
in the file contents. Which is it? Can you clarify?
PS:你的问题有点不清楚。您a
在文件名中发布测试的代码(我的代码也是如此)。但是您的文字表明您要a
在文件内容中搜索。是哪个?你能澄清一下吗?
回答by Kusalananda
You need space after [[
and before ]]
:
[[
前后需要空间]]
:
for file in *.out;do
if [[ "$file" == *"$STRING"* ]];then
printf '%s\n' "$file"
fi
done
or just
要不就
for file in *"$STRING"*.out; do
printf '%s\n' "$file"
done
or
或者
printf '%s\n' *"$STRING"*.out