Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I process the results of find in a bash script?

Tags:

find

bash

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?

like image 985
Shellscriptbeginner Avatar asked Jan 18 '10 15:01

Shellscriptbeginner


People also ask

How do you store output of find command in 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.

How does find work in bash?

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).

How do you store output of find command in a variable in Linux?

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 ...]


2 Answers

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 
like image 93
Johannes Weiss Avatar answered Nov 15 '22 23:11

Johannes Weiss


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 
like image 39
starpause Avatar answered Nov 16 '22 00:11

starpause