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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With