【发布时间】:2011-09-01 07:10:57
【问题描述】:
我正在使用循环来读取数组的内容,该数组包含名为“music”的目录层次结构中的所有目录和文件(内容是“find”命令的先前输出的字符串)。这个想法是根据流派、艺术家和标题将“directory_contents”中每个数组元素的完整目录路径分成子字符串。由于我的音乐目录首先按流派排序,然后按艺术家排序,然后按标题排序,因此我使用 awk 抓取每个相关项目,其中分隔符“/”出现。例如,如果使用 find "./Electronic/Squarepusher/My Red Hot Car.aif" 后目录看起来像这样,我将把 "Electronic"、"Squarepusher" 和 "My Red Hot Car" 分开,然后分别存储在流派、艺术家和标题的单独数组中。稍后我将对这些数据进行排序,然后将排序后的输出通过管道传输到另一个实用程序中,以在一个漂亮的表中打印所有目录内容(还没有这样做)。目前,我只是尝试使用 echo 语句查看字符串分离的结果,并且在大多数情况下它似乎有效。但是,我似乎无法提取包含空格的子字符串,这不好:
-->./Hip-Hop/OutKast/title1.aif<--
Genre:
Hip-Hop
Artist:
OutKast
Title:
title1
-->./Hip-Hop/OutKast/title2.aif<--
Genre:
Hip-Hop
Artist:
OutKast
Title:
title2
-->./Hip-Hop/OutKast/title3.aif<--
Genre:
Hip-Hop
Artist:
OutKast
Title:
title3
-->./Jazz/John<--
Genre:
Jazz
Artist:
John
Title:
-->Coltrane/title1.aif<--
Genre:
title1.aif
Artist:
Title:
如您所见,当循环读取字符串“John Coltrane”时,它将空格视为分隔符,并将“John”之后的所有内容视为不同的文件名。我尝试在“数组”部分以及此处的其他帖子下的 bash 手册中寻找解决方案,但找不到适用于我的特定问题的解决方案(抱歉)。如果有人有想法,他们将不胜感激。有问题的代码出现在下面的 for 循环中(我没有发布整个脚本,因为它很长,但如果需要,请告诉我):
#more before this...
#declare variables
declare -a genre_list
declare -a title_list
declare -a artist_list
declare -a directory_contents
#populate directory with contents
cd $directory
directory_contents=$(find . -mindepth 1 -type f)
cd ..
for music_file in ${directory_contents[*]}; do
if [[ $DEBUG = "true" ]] ; then
echo "-->$music_file<--"
fi
echo "Genre:"
echo $music_file | awk -F"/" '{print $2}'
echo "Artist:"
echo $music_file | awk -F"/" '{print $3}'
echo "Title:"
echo $music_file | awk -F"/" '{print $4}' | awk -F"." '{print $1}'
echo ""
done
【问题讨论】:
标签: arrays bash string for-loop awk