sr320 / course-fish546-2016

6 stars 5 forks source link

appending `find` results to a bash array #97

Closed mfisher5 closed 7 years ago

mfisher5 commented 7 years ago

I'm working on part of a simple bash script to append results from a find expression into a bash array titled file_array. When I run the find expression by itself, it returns all files in the folder that end in ".fq.gz" -- but when I run the find expression and then append to an array, it only appends the first file in the folder. Here is the code:

(1) find expression, printing to command line find . -name "*fq.gz"

(2) find results into bash array read -a file_array <<< "$(find . -name "*.fq.gz")" echo ${#file_array[@]} #to print out length of array; prints out 1

I've tried looking through stack overflow, but I can't seem to find anything that explains why it is not working!

kubu4 commented 7 years ago

@mfisher5, I think you had it nearly correct in your initial layout (sorry!). Try something like this:

file_array=($(find . -name "*.txt"))

Also, in addition to testing your initial array by length, you can try printing the contents. Based off of your array length results, I'm guessing all the results from your find command are a single entry in your array; thus, an array length of one.

kubu4 commented 7 years ago

Updated my previous comment (left out the all important =)! Sorry!

mfisher5 commented 7 years ago

That worked! Thank you!

kubu4 commented 7 years ago

Also to note, the find command will print the path to the files. So, the contents of your array will end up being something like this:

INPUT: echo ${file_array[0]}
OUTPUT: ./3rd.txt
INPUT: echo ${file_array[1]}
OUTPUT: ./second.txt

Most likely, you'll need (want) to get rid of the leading path before your file name. This is where basename or parameter substitution is handy.