Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through files in a directory having a certain word in filename using bash script?

Tags:

bash

loops

I'm trying to loop through all the files in a directory which contain a certain word in filename using bash script.

The following script loops through all the files in the directory,

cd path/to/directory

for file in *
do
  echo $file
done

ls | grep 'my_word' gives only the files which have the word 'my_word' in the filename. However I'm unsure how to replace the * with ls | grep 'my_word' in the script.

If i do like this,

for file in ls | grep 'my_word'
do
  echo $file
done 

It gives me an error "syntax error near unexpected token `|'". What is the correct way of doing this?

like image 335
Senthil Kumar Avatar asked Dec 27 '22 19:12

Senthil Kumar


1 Answers

You should avoid parsing ls where possible. Assuming there are no subdirectories in your present directory, a glob is usually sufficient:

for file in *foo*; do echo "$file"; done

If you have one or more subdirectories, you may need to use find. For example, to cat the files:

find . -type f -name "*foo*" | xargs cat

Or if your filenames contain special characters, try:

find . -type f -name "*foo*" -print0 | xargs -0 cat

Alternatively, you can use process substitution and a while loop:

while IFS= read -r myfile; do echo "$myfile"; done < <(find . -type f -name '*foo*')

Or if your filenames contain special characters, try:

while IFS= read -r -d '' myfile; do
  echo "$myfile"
done < <(find . -type f -name '*foo*' -print0)
like image 99
Steve Avatar answered Apr 09 '23 22:04

Steve