How do I store the output from a find command in an array? + bash
我有下面的find命令,输出如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | $ find -name '*.jpg' ./public_html/github/screencasts-gh-pages/reactiveDataVis/presentation/images/telescope.jpg ./public_html/github/screencasts-gh-pages/introToBackbone/presentation/images/telescope.jpg ./public_html/github/StarCraft-master/img/Maps/(6)Thin Ice.jpg ./public_html/github/StarCraft-master/img/Maps/Snapshot.jpg ./public_html/github/StarCraft-master/img/Maps/Map_Grass.jpg ./public_html/github/StarCraft-master/img/Maps/(8)TheHunters.jpg ./public_html/github/StarCraft-master/img/Maps/(2)Volcanis.jpg ./public_html/github/StarCraft-master/img/Maps/(3)Trench wars.jpg ./public_html/github/StarCraft-master/img/Maps/(8)BigGameHunters.jpg ./public_html/github/StarCraft-master/img/Maps/(8)Turbo.jpg ./public_html/github/StarCraft-master/img/Maps/(4)Blood Bath.jpg ./public_html/github/StarCraft-master/img/Maps/(2)Switchback.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(6)Thin Ice.jpg ./public_html/github/StarCraft-master/img/Maps/Original/Map_Grass.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(8)TheHunters.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(2)Volcanis.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(3)Trench wars.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(8)BigGameHunters.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(8)Turbo.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(4)Blood Bath.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(2)Switchback.jpg ./public_html/github/StarCraft-master/img/Maps/Original/(4)Orbital Relay.jpg ./public_html/github/StarCraft-master/img/Maps/(4)Orbital Relay.jpg ./public_html/github/StarCraft-master/img/Bg/GameLose.jpg ./public_html/github/StarCraft-master/img/Bg/GameWin.jpg ./public_html/github/StarCraft-master/img/Bg/GameStart.jpg ./public_html/github/StarCraft-master/img/Bg/GamePlay.jpg ./public_html/github/StarCraft-master/img/Demo/Demo.jpg ./public_html/github/flot/examples/image/hs-2004-27-a-large-web.jpg ./public_html/github/minicourse-ajax-project/other/GameLose.jpg |
如何将此输出存储在数组中?我要它处理带有空格的文件名
我试过这个
1 2 3 4 | $ arrayname=($(find -name '*.jpg')) $ echo"$arrayname" ./public_html/github/screencasts-gh-pages/reactiveDataVis/presentation/images/telescope.jpg $ |
我在这里试过了,但这只存储了第一个元素
其他类似问题如何从ls或find命令捕获输出以将所有文件名存储在数组中?如何将bash命令的输出存储在变量中?
如果您确信您的文件名不会包含换行符,那么
1 | mapfile -t arrayname < <(find ...) |
如果你想处理任何文件
1 2 3 4 | arrayname=() while IFS= read -d '' -r filename; do arrayname+=("$filename") done < <(find ... -print0) |
1 2 3 | printf"%s ""${arrayname[@]}" # ............^^^^^^^^^^^^^^^^^ must use exactly this form, with the quotes. |
如果您有一个足够新的bash版本,那么您只需使用
1 2 | shopt -s globstar files=(**/*.jpg) |
第一行启用该功能。一旦启用,glob模式中的
在数组定义中使用glob可以确保正确处理空白。
要以可用于定义数组的形式查看数组,请使用
1 | declare -p files |