How to loop through file names returned by find?

前端 未结 13 1433
野性不改
野性不改 2020-11-22 04:20
x=$(find . -name \"*.txt\")
echo $x

if I run the above piece of code in Bash shell, what I get is a string containing several file names separated

13条回答
  •  情书的邮戳
    2020-11-22 04:50

    If you can assume the file names don't contain newlines, you can read the output of find into a Bash array using the following command:

    readarray -t x < <(find . -name '*.txt')
    

    Note:

    • -t causes readarray to strip newlines.
    • It won't work if readarray is in a pipe, hence the process substitution.
    • readarray is available since Bash 4.

    Bash 4.4 and up also supports the -d parameter for specifying the delimiter. Using the null character, instead of newline, to delimit the file names works also in the rare case that the file names contain newlines:

    readarray -d '' x < <(find . -name '*.txt' -print0)
    

    readarray can also be invoked as mapfile with the same options.

    Reference: https://mywiki.wooledge.org/BashFAQ/005#Loading_lines_from_a_file_or_stream

提交回复
热议问题