I'm trying to use an array to store a list of file names using the find
command.
For some reason the array fails to work in the bash used by the school, my program works on my own laptop though.
So I was wondering if there's another way to do it, this is what i have:
array = (`find . -name "*.txt"`) #this will store all the .txt files into the array
Then I can access the array items and make a copies of all the files using the cat command.
Is there another way to do it without using an array?
The array+=("$REPLY") statement appends the new file name to the array array . The final line combines redirection and command substitution to provide the output of find to the standard input of the while loop.
The Bash find Command 101 Finding a file requires some criteria; a part of the file name, a file type, permissions on the file, etc. The find command allows you to define those criteria to narrow down the exact file(s) you'd like to find. The find command finds or searches also for symbolic links (symlink).
To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]
You could use something like this:
find . -name '*.txt' | while read line; do echo "Processing file '$line'" done
For example, to make a copy:
find . -name '*.txt' | while read line; do echo "Copying '$line' to /tmp" cp -- "$line" /tmp done
I was having issue with Johannes Weiß's solution, if I was just doing an echo it would work for the full list of files. However, if I tried running ffmpeg on the next line the script would only process the first file it encountered. I assumed some IFS funny business due to the pipe but I couldn't figure it out and ran with a for loop instead:
for i in $(find . -name '*.mov' ); do echo "$i" done
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