简体   繁体   English

搜索在Bash中包含特定字符串的特定扩展名文件名

[英]Search specific extension filenames that contain a particular string in Bash

I'd like to search in one Linux folder all the py files that contain the string "2" in their names. 我想在一个Linux文件夹中搜索所有名称中包含字符串“ 2”的py文件。

I began with the following code : 我从以下代码开始:

for file in /home/sig/*.py;
do echo "$file is present"; 
done

But I don't see how to add the string search condition. 但是我看不到如何添加字符串搜索条件。

Could you help me ? 你可以帮帮我吗 ?
Thanks ! 谢谢 !

You can use find : 您可以使用find

find /home/sig/ -type f -name "*2*.py"

BTW, sh != Bash . 顺便说一句, sh != Bash You tagged your question with but you are asking about Bash in your question. 您用标记了您的问题,但您在问题中询问的是Bash

EDIT: 编辑:

Execute every file: 执行每个文件:

find /home/sig/ -type f  -name "*2*.py" -exec {} \;
echo /home/sig/*2*.py

or 要么

ls /home/sig/*2*.py

or 要么

for file in /home/sig/*2*.py; do
  echo "$file was present"  # inherent race condition
done

The loop is not terribly reliable, as the file may exist when the shell performs the glob expansion to get the list of files, but it may not exist by the time the 'echo' is executed. 循环并不是十分可靠,因为当外壳程序执行glob扩展以获取文件列表时文件可能存在,但是在执行“ echo”时可能不存在。 This is probably an academic concern for your use case, but can often be a source of real errors. 这可能是您的用例的学术问题,但通常可能是真正错误的来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM