Julien
Julien

Reputation: 629

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.

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 !

Upvotes: 2

Views: 179

Answers (2)

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12548

You can use find:

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

BTW, sh != Bash. You tagged your question with but you are asking about Bash in your question.

EDIT:

Execute every file:

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

Upvotes: 2

William Pursell
William Pursell

Reputation: 212634

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. This is probably an academic concern for your use case, but can often be a source of real errors.

Upvotes: 2

Related Questions