How can I store the “find” command results as an array in Bash

后端 未结 8 1769
刺人心
刺人心 2020-11-22 16:29

I am trying to save the result from find as arrays. Here is my code:

#!/bin/bash

echo \"input : \"
read input

echo \"searching file with this          


        
相关标签:
8条回答
  • 2020-11-22 17:00

    Bash 4.4 introduced a -d option to readarray/mapfile, so this can now be solved with

    readarray -d '' array < <(find . -name "$input" -print0)
    

    for a method that works with arbitrary filenames including blanks, newlines, and globbing characters. This requires that your find supports -print0, as for example GNU find does.

    From the manual (omitting other options):

    mapfile [-d delim] [array]

    -d
    The first character of delim is used to terminate each input line, rather than newline. If delim is the empty string, mapfile will terminate a line when it reads a NUL character.

    And readarray is just a synonym of mapfile.

    0 讨论(0)
  • 2020-11-22 17:10

    For me, this worked fine on cygwin:

    declare -a names=$(echo "("; find <path> <other options> -printf '"%p" '; echo ")")
    for nm in "${names[@]}"
    do
        echo "$nm"
    done
    

    This works with spaces, but not with double quotes (") in the directory names (which aren't allowed in a Windows environment anyway).

    Beware the space in the -printf option.

    0 讨论(0)
提交回复
热议问题