[mdlug] Need help with bash array usage

Michael Corral micorral at comcast.net
Wed Jul 9 13:32:26 EDT 2008


2008-07-08, Monsieur Jeff Hanson a ecrit:
> Sample script and directories attached.  I'm trying to find files with
> a specific filename extension, containing a specific string, in a
> directory tree where directory and file names may contain spaces, then
> put it into an array with one complete path per element.  I can obtain
> a list with quoted paths and use command substitution to load it into
> the array but the assignment ignores the quotes and each element gets
> a space-delimited substring.  I think it's a word-splitting problem
> but am not sure how to fix it.

Try the modified script below:

#!/bin/bash
declare -a matching_files
IFS="$(echo -e "\n\r")"
matching_files=($(find . -type f -iname "*.txt" -exec grep -l "MATCH" '{}' \;| sed -n 's/\(.*\)$/\"\1\"/p'))
unset IFS
x=0
while test ${#matching_files[$x]} -ne 0
do
echo $x": "${matching_files[$x]}
((x++))
done
exit 0

I just tested it on your files and it works:

$ ./arraywordtest.sh
0: "./test test1/test2.txt"
1: "./test/testfile 1.txt"
2: "./testy test test/sub dir/test.txt"

What I did was set the internal field separator (IFS) to split lines by
newlines instead of spaces (the default). Doing that means you don't
need to pipe the sed command to tr anymore.

Michael



More information about the mdlug mailing list