4

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?

2
  • 1
    The correct syntax would be for file in $(ls | grep 'my_word'); do, but using find or a glob` is still the correct way to go. Commented Aug 9, 2012 at 11:59
  • yes, thanks, figured that out later with the help of steve's answer :) Commented Aug 9, 2012 at 13:28

1 Answer 1

11

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)
Sign up to request clarification or add additional context in comments.

4 Comments

thanks first one works. how do i use the second one in for loop? that's what i don't know. i want to substitute the function result in the place of *.
figured it out, files=find . -type f -name "*my_word*" | xargs cat and for file in $files works! thanks!
@Steve Is the no-parsing-ls thing a security issue? A file/dir name could be a command that sends all to oblivion?
@t0mgs: I wouldn't call it a security issue. Those problems exist when parsing any input. Parsing ls should just be avoided where possible, as the output can't always be trusted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.