[mdlug] Need help with bash array usage

Jeff Hanson jhansonxi at gmail.com
Wed Jul 9 19:36:55 EDT 2008


On Wed, Jul 9, 2008 at 1:32 PM, Michael Corral <micorral at comcast.net> wrote:
> 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.

That works!  The only problem was that the sed command was embedding
extra double-quotes so I fixed it.  Your IFS solution was similar to
other suggestions I found but couldn't figure out how to utilize it
properly.

-----------------------------------------------
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
set | less
exit 0
-----------------------------------------------

Using "set | less" reveals:
matching_files=([0]="./testy test test/sub dir/test.txt"
[1]="./test/testfile 1.txt" [2]="./test test1/test2.txt")



More information about the mdlug mailing list