How to loop through file names returned by find?

前端 未结 13 1339
野性不改
野性不改 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:46

    You can store your find output in array if you wish to use the output later as:

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

    Now to print the each element in new line, you can either use for loop iterating to all the elements of array, or you can use printf statement.

    for i in ${array[@]};do echo $i; done
    

    or

    printf '%s\n' "${array[@]}"
    

    You can also use:

    for file in "`find . -name "*.txt"`"; do echo "$file"; done
    

    This will print each filename in newline

    To only print the find output in list form, you can use either of the following:

    find . -name "*.txt" -print 2>/dev/null
    

    or

    find . -name "*.txt" -print | grep -v 'Permission denied'
    

    This will remove error messages and only give the filename as output in new line.

    If you wish to do something with the filenames, storing it in array is good, else there is no need to consume that space and you can directly print the output from find.

提交回复
热议问题